[英]Issues with Long in Hashtable Java
显然,我无法在哈希表中存储Long值。
请参见下面的代码:
//create a hashtable of type <String, Long>
Hashtable <String, Long> universalTable = new Hashtable <String, Long> ();
universalTable.put("HEADS", new Long(0)); // this works fine
我将此表传递给DoFlip
的构造DoFlip
:
DoFlip doFlip = new DoFlip(100000000, universalTable);
内部DoFlip
:
Hashtable table; // pointer to hash map
long iterations = 0; // number of iterations
DoFlip(long iterations, Hashtable table){
this.iterations = iterations;
this.table = table;
}
此类实现Runnable。 run()
方法如下:
public void run(){
while(this.iterations > 0){
// do some stuff
this.heads ++;
this.iterations --;
}
updateStats();
}
public void updateStats(){
Long nHeads = (Long)this.table.get("HEADS");
this.table.put("HEADS", nHeads); // ISSUE HERE
}
我收到以下警告/错误。 看起来像是警告,但我不想要这个。
Note: File.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
当我重新编译时:
File.java:92: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Hashtable
this.table.put("HEADS", nHeads);
^
1 warning
我不确定为什么会这样。 首先,不需要键入nHeads
。 但是我仍然这样做,并且不起作用。
注意:我一点都不擅长Java。 :/
谢谢您的帮助。
此警告表明您正在使用原始类型。 更换
DoFlip(long iterations, Hashtable table){
与
DoFlip(long iterations, Hashtable<String, Long> table) {
这样它就包含类似于universalTable
的泛型。 还应在初始声明中包含泛型。
边注:
Hashtable
是一个相当老的Collection
,已由HashMap
取代。 这只是一个警告,告诉您正在混合通用容器和非通用容器。 这是允许的,但是如果您在代码的任何地方都使用泛型,则编译器可以在类型检查方面做得更好。
要解决此警告,您需要进行更改
Hashtable table;
对于
Hashtable<String, Long> table;
在DoFlip
内的DoFlip
。
我的2美分:
首先,如果要构建一些对性能敏感的应用程序,并且希望避免在Long和long原语之间进行转换,请考虑使用trove4j集合库。 它是基于原始的,质量很高。
其次,您的DoFlip应该声明为
DoFlip(long iterations, Hashtable<String, Long> table){
this.iterations = iterations;
this.table = table;
}
问题解决了。
请享用。
您需要向编译器保证,您的HashMap都是从Strings到Longs。 您是在这里完成的:
Hashtable <String, Long> universalTable = new Hashtable <String, Long> ();
...但不在这里:
Hashtable table; // pointer to hash map
---
DoFlip(long iterations, Hashtable table){
这样:
Hashtable<String, Long> table;
---
DoFlip(long iterations, Hashtable<String, Long> table){
...并且不再会有自动恐慌,您会在运行时将错误类型的对象放入table
中,因为现在编译器可以检查您始终使用所需的对象(即括号中指定的对象)。
这只是来自编译器的警告,提示您mixing generic and non-generic containers
您可以执行以下任一步骤使其消失
1)您需要更改
Hashtable table;
对于
Hashtable<String, Long> table;
要么
2)您可以使用SuppressWarning注释来禁止显示警告
@SuppressWarnings("unchecked")
public void updateStats(){
Long nHeads = (Long)this.table.get("HEADS");
this.table.put("HEADS", nHeads); // ISSUE HERE
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.