Java 哪个对象引用初始化为Dictionary类类型引用变量?
我创建了一个类DictionaryTest,将元素及其对应的键添加到字典中,并显示字典中的所有元素和键。下面是我的代码:Java 哪个对象引用初始化为Dictionary类类型引用变量?,java,dictionary,Java,Dictionary,我创建了一个类DictionaryTest,将元素及其对应的键添加到字典中,并显示字典中的所有元素和键。下面是我的代码: import java.util.Dictionary; import java.util.Enumeration; public class DictonaryTest { public static void main(String[] args) { Dictionary d; d.put(new
import java.util.Dictionary;
import java.util.Enumeration;
public class DictonaryTest
{
public static void main(String[] args)
{
Dictionary d;
d.put(new Integer(1),new Integer(100));
d.put(new Integer(2),new Integer(200));
d.put(new Integer(3),new Integer(300));
d.put(new Integer(4),new Integer(400));
d.put(new Integer(5),new Integer(500));
System.out.println("Size of dictionary : " + d.size());
Enumeration ekey = d.keys();
Enumeration eelement = d.elements();
System.out.println("Keys in the Dictionary...");
while(ekey.hasMoreElements()){
System.out.println(ekey.nextElement() + "\t");
}
System.out.println("Elements in the Dictionary...");
while(eelement.hasMoreElements()){
System.out.println(eelement.nextElement() + "\t");
}
}
}
但这里将显示编译错误,如下所示:
局部变量d可能尚未初始化。
在爪哇中,什么对象引用被初始化为字典类类型引用变量?,不同于C++,声明变量不初始化它。你必须手动操作
Dictionary d = new Dictionary();
编辑:字典
是一个抽象类,因此您应该使用它的实现。其实是现在,;你应该改用。同样的道理
Map d = new HashMap();
您还应该使用可能的泛型:
Map<Integer,Integer> d = new Map<Integer,Integer>();
您必须编写一个类扩展字典或使用
Dictionary<Integer,Integer> d = new HashTable<Integer,Integer>();
Dictionary d=newhashtable();
但既然它已经过时了:为什么不使用地图呢
Map d=newhashmap();
设置键=d.键集();
集合值=d.值();
您可以像处理字典对应项一样轻松地处理它们。下面的工作(请参见带有
//的行,但字典是一个抽象类,它不能由构造函数初始化。字典
是抽象的,不能实例化。此外,from()“注意:此类已过时。新实现应实现映射接口,而不是扩展此类。”@DavidPostill。
Dictionary<Integer,Integer> d = new HashTable<Integer,Integer>();
Map<Integer,Integer> d = new HashMap<>();
Set<Integer> keys = d.keySet();
Collection<Integer> values = d.values();
import java.util.Dictionary;
import java.util.Hashtable; // <-- Needed for Hashtable
import java.util.Enumeration;
public class DictonaryTest
{
public static void main(String[] args)
{
Dictionary d = new Hashtable(); // <-- Initialise d with a Hashtable
d.put(new Integer(1),new Integer(100));
d.put(new Integer(2),new Integer(200));
d.put(new Integer(3),new Integer(300));
d.put(new Integer(4),new Integer(400));
d.put(new Integer(5),new Integer(500));
System.out.println("Size of dictionary : " + d.size());
Enumeration ekey = d.keys();
Enumeration eelement = d.elements();
System.out.println("Keys in the Dictionary...");
while(ekey.hasMoreElements()){
System.out.println(ekey.nextElement() + "\t");
}
System.out.println("Elements in the Dictionary...");
while(eelement.hasMoreElements()){
System.out.println(eelement.nextElement() + "\t");
}
}
}