我正在尝试建立一个构造函数,其中使用的数据结构将由参数::中的字符串确定
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();
}
Run Code Online (Sandbox Code Playgroud)
在运行代码时,无论我放入什么,我都会得到"UnsuportedOperationException".非常感谢任何帮助或正确方向上的一点.(代码是Java)
显而易见的答案是
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();
}
Run Code Online (Sandbox Code Playgroud)
因为st1和st2你的代码将落到throw.
也就是说,这种方法通常很糟糕.作为参考看看Java集合接口(Map<K,V>例如)和它的实现(HashMap,TreeMap,等).