2012-04-03 36 views
0

我试图运行代码我得到“UnsuportedOperationException”时设立地方使用的数据结构将确定一个字符串中的参数::多个构造与相同参数

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(); 
    } 

构造不管我输入什么东西。任何帮助或正确的方向点将不胜感激! (代码是Java)

+0

小心给我们st1,st2和st3? – 2012-04-03 03:14:25

+0

st1 =“linkedlist” st2 =“hash” st3 =“array” – JeffS 2012-04-03 17:01:26

回答

6

答案显然是

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(); 
} 

对于st1st2您的代码将始终陷入throw

也就是说,这种方法通常是不好的。参考Java收集接口(例如Map<K,V>)及其实现(HashMap,TreeMap等)。

+1

看看您的原始文章 - 您遗漏了'else'关键字。 – 2012-04-03 03:26:49

+0

如果你想坚持这种方法,至少考虑切换到字典类型的枚举而不是硬编码字符串 – Robin 2012-04-03 05:43:01

+0

奇怪的是,我最初尝试了它与其他如果,它没有工作,虽然它现在工作因为我问过你们(奇怪的是,在这里以及在IT服务台工作的情况如何,尽管我的probalby也在我之前的代码中做了错误处理)。 这是一个学校项目,所以不允许使用Java集合,并且必须自己编写数据结构。 感谢您的帮助! – JeffS 2012-04-03 16:56:23