Java 如何创建集合对象并向其中添加元素
如何创建集合对象并向其中添加元素 我是这样做的:Java 如何创建集合对象并向其中添加元素,java,collections,Java,Collections,如何创建集合对象并向其中添加元素 我是这样做的: Collection col = Collections.EmptyList(); col.add("String1"); 但它会抛出UnspoortedOperationException,因为EmptyList()将创建一个无法更改的不可变对象。集合只是存储其他对象的对象的接口。您必须使用实际的实现(如哈希集)来实例化它。例如: Collection<String> col = new HashSet<String>
Collection col = Collections.EmptyList();
col.add("String1");
但它会抛出UnspoortedOperationException,因为EmptyList()将创建一个无法更改的不可变对象。
集合
只是存储其他对象的对象的接口。您必须使用实际的实现(如哈希集)来实例化它。例如:
Collection<String> col = new HashSet<String>();
col.add("String1");
Collection col=newhashset();
第1栏(“第1条”);
请注意,还必须提供要存储的对象的类型,如
字符串
、列表
或对象
。有关更多信息,请参阅。您应该指定收藏类型
这样试试
1.Collection<String> col = new Arraylist<>();
col.add("String1");
2.List<String> col = new ArrayList<>();
col.add("String1");
1.Collection col=new Arraylist();
第1栏(“第1条”);
2.List col=new ArrayList();
第1栏(“第1条”);
Collections.EmptyList()创建一个空列表,您无法在其中添加更多对象。
必须通过指定列表类型来创建,如:
Collection<String> col = new ArrayList<String>();
col.add("String1");
Collection col=newarraylist();
第1栏(“第1条”);
集合不是一个具体的对象类,它只是一个接口,您必须创建实现集合接口的任何集合具体类,如HashSet、ArrayList等
public static void main(String args[]) throws Exception {
Collection col = new ArrayList<>();
col.add("String1");
System.out.println(col.toString());
}
publicstaticvoidmain(字符串args[])引发异常{
Collection col=new ArrayList();
第1栏(“第1条”);
System.out.println(col.toString());
}
您正在定义一个原始类型集合,如果您不想给类指定规格,则不建议这样做