Reputation: 3
I'm trying to set up a constructor where a the data structure used will be determined by a string in the parameter::
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();
}
when running the code I get "UnsuportedOperationException" no matter what I put in. Any help or a point in the right direction would be greatly appreciated! (Code is in Java)
Upvotes: 0
Views: 939
Reputation: 86774
The obvious answer is
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();
}
For st1
and st2
your code would fall through to the throw
.
That said, this approach is generally bad. For reference look at the Java collection interfaces (Map<K,V>
for instance) and its implementations (HashMap
, TreeMap
, etc).
Upvotes: 6