编译时错误,当使用“新双”
问题描述:
我创建了一个哈希表,我试图使用枚举为了打印出键和值。当我尝试编译代码时,我不断收到编译时错误,说我需要在新的double中放入一个'['',放入哈希表中。 toys.put(“Race Car”,new double(29.99));以及其他玩具。编译时错误,当使用“新双”
编译时错误说我需要把它像这样:
toys.put( “赛车”,新的双[29.99]);
我在做什么错?
public static void main(String[] args) {
Hashtable toys = new Hashtable();
Enumeration toyName;
String getToyName;
double priceOfToy;
toys.put("Race Car", new double(29.99));
toys.put("Toy Bear", new double(15.99));
toys.put("Action Figure", new double(9.99));
//Show prices of each toy
toyName = toys.keys();
//Uses hasMoreElements method from enumeration to check what is in the hashtable
while (toyName.hasMoreElements()) {
//uses nextElement method from enumeration interface to
getToyName = (String) toyName.nextElement();
System.out.println(getToyName + "is now priced at " + toys.get(getToyName));
}
}
答
地图只接受对象,而不是基元,double是基元,Double是对象。 ,也可以考虑使用泛型类型为您的集合:
Hashtable<String, Double> toys = new Hashtable<String, Double>();
toys.put("Race Car", new Double(29.99));
toys.put("Toy Bear", new Double(15.99));
toys.put("Action Figure", new Double(9.99));}
答
double
是原始类型。改为使用包装类Double
。由于泛型的限制,集合不能保存原始类型的值,所以必须使用包装器。
编译器显示此警告,因为它假设您想实例化一个数组,可以使用new double [22]
来完成。另外,如果您使用Java 1.5或更高版本,则只需使用原始值代替包装值,它们就会自动转换为包装对象。
答
一个包装了double
是Double
(大小写很重要)的类。
所以:
toys.put("Race Car", new Double(29.99));
或者,由于Java 5中,自动装箱(转换双自动双)被suuported,所以
toys.put("Race Car", 29.99d));
是完全一样的。
答
Java集合不能保存原始类型。您需要更改
toys.put("Race Car", new double(29.99))
到
toys.put("Race Car", new Double(29.99))
它使用Double
包装类型。
您还可以使用具有简单
toys.put("Race Car", 29.99)
请注意,我没有测试过这最后一个,以确保它的工作原理自动装箱。
答
要么使用Double
类
toys.put("Race Car", new Double(29.99));
toys.put("Toy Bear", new Double(15.99));
toys.put("Action Figure", new Double(9.99));
或Java基本double
toys.put("Race Car", 29.99); // Java 1.5 or higher, makes use of inboxing
toys.put("Toy Bear", 15.99);
toys.put("Action Figure", 9.99);
Java基本没有类和没有构造函数。
你还在使用Java 1.4吗? – fge
我对Java仍然很陌生,我在哪里检查? – Jay
你不能'new'原始类型。但是,由于自动装箱(自1.5开始),只需使用:'toys.put(“Minigun”,999.99)'。此外,请在问题中包含* exact *复制粘贴错误消息。 – 2013-01-09 22:54:28