我有一个Vector
像这样:
Vector myVector = new Vector();
还有一个ArrayList
包含 n
的自定义类的金额String
s。
基本上,我将一个空项目添加到 vector ( myVector.insertElementAt("", 0);
) 中的第一个位置,然后添加(通常) ArrayList
中的其余项目。 (取决于需要)。这个Vector
然后用作DefaultComboBoxModel
对于JComboBox
.
现在,我收到了常见的警告对泛型类型 Vector 的引用应该参数化。
这些项目的类型为 String
,但我不能使用Vector<String>
因为添加 ArrayList
中的项目(使用 .add()
)将不起作用:
Vector(String) 类型中的 add(String) 方法不适用于参数 (CustomClass)。
我无法使用 Vector(CustomClass)
因为那时insertElementAt
抛出一个摇晃器。
所以我的问题是:仅使用 Vector(Object)
是否安全?或者根本不参数化类型?
我可以使用T
并强制转换所有内容,但会出现类型安全错误。
最佳答案
I can't use Vector because adding the items from the ArrayList (using .add()) won't work as:
block 引用>The method add(String) in the type Vector(String) is not applicable for the arguments (CustomClass).
所以,您正在尝试从
ArrayList<CustomClass>
添加内容到Vector
您期望仅包含String
元素。如果您使用的是原始类型
Vector
,您可以执行此操作,但如果您尝试对Vector
中的元素执行任何操作,则会失败。您将其视为String
,因为它不是。如果你想要
Vector
包含String
s,添加String
:myVector.add(thingFromArrayList.toString());
(或将
thingFromArrayList
转换为String
的其他方法)然后您可以添加
<String>
至myVector
的类型。
关于java - 参数化原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49424041/