我正在尝试设置一个构造函数,其中所使用的数据结构将由参数中的字符串确定::
DictionaryI<IPAddress,String> ipD; //declaring main structure using interface
// Constructor, the type of dictionary to use (hash, linkedlist, array)
// and the initial size of the supporting dictionary
public IPManager(String dictionaryType, int initialSize){
if(st1.equals(dictionaryType))
ipD = new LinkedListDictionary();
if(st2.equals(dictionaryType))
ipD = new HashDictionary(initialSize);
if(st3.equals(dictionaryType))
ipD = new ArrayDictionary(initialSize);
else
throw new UnsupportedOperationException();
}
在运行代码时,无论我放入什么,我都会得到"UnsuportedOperationException“。任何帮助或在正确的方向上的一点都将非常感谢!(代码用Java编写)
发布于 2012-04-03 11:07:08
显而易见的答案是
public IPManager(String dictionaryType, int initialSize){
if(st1.equals(dictionaryType))
ipD = new LinkedListDictionary();
else if(st2.equals(dictionaryType))
ipD = new HashDictionary(initialSize);
else if(st3.equals(dictionaryType))
ipD = new ArrayDictionary(initialSize);
else
throw new UnsupportedOperationException();
}
对于st1
和st2
,您的代码将会落入throw
。
也就是说,这种方法通常是不好的。作为参考,请查看Java集合接口(例如Map<K,V>
)及其实现(HashMap
、TreeMap
等)。
https://stackoverflow.com/questions/9986567
复制相似问题