gpt4 book ai didi

java - 具有相同参数的多个构造函数

转载 作者:行者123 更新时间:2023-12-01 16:35:11 26 4
gpt4 key购买 nike

我正在尝试设置一个构造函数,其中使用的数据结构将由参数中的字符串确定::

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

运行代码时,无论我输入什么内容,我都会收到“UnsupportedOperationException”。任何帮助或正确方向的观点将不胜感激! (代码是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();
}

对于st1st2您的代码将落入 throw .

也就是说,这种方法通常很糟糕。作为引用,请查看 Java 集合接口(interface)(例如 Map<K,V>)及其实现( HashMapTreeMap 等)。

关于java - 具有相同参数的多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9986567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com