[英]Multiple Constructors with same arguments
我正在嘗試建立一個構造函數,其中使用的數據結構將由參數中的字符串確定:
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)
顯而易見的答案是
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
等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.