Collection集合
集合是java提供的一种容器,可以存储多个数据。
集合和数组的区别?
1、数组的长度是固定的,集合是可变的,随着数据加而加。
2、数组存储的是同一种类型,可以存储基本数据类型的值,而集合存储的都是对象,而且对象的类型可以不一致,一般开发对象多的话,会用集合。
集合框架图
collection的一些方法的使用
import java.util.ArrayList;
import java.util.Collection;
public class Dem1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection<String> coll = new ArrayList();
System.out.println(coll);// [] 说明重写了toString方法
//public boolean add(E e);
//确保此集合包含指定的元素(可选操作)。
//如果此集合由于调用而更改,则返回true 。
//(如果此集合不允许重复,并且已包含指定的元素,则返回false。 )
coll.add("战士");//增加
coll.add("勇士");
coll.add("詹皇");
coll.add("杰克");
coll.add("肉丝");
coll.add("老王");
System.out.println(coll);//[战士, 勇士, 詹皇, 杰克, 肉丝, 老王]
//public boolean remover(E e)
//删除指定集合中包含的所有此集合的元素(可选操作)。 此调用返回后,此集合将不包含与指定集合相同的元素。
boolean remove = coll.remove("肉丝");
System.out.println("remove: "+remove);//remove: true
System.out.println(coll);//[战士, 勇士, 詹皇, 杰克, 老王]
//public boolean cotains(E e)
//如果此集合包含指定的元素,则返回true 。
boolean contains = coll.contains("老王");
System.out.println(contains);//true
//public boolean isEmpty();
//如果此集合不包含元素,则返回 true 。
boolean empty = coll.isEmpty();
System.out.println(empty);//false
//public int size();
//返回此集合中的元素数。 如果此收藏包含超过Integer.MAX_VALUE个元素,则返回Integer.MAX_VALUE 。
int size = coll.size();
System.out.println(size);
//public Object toArray()
//返回一个包含此集合中所有元素的数组。
Object[] array = coll.toArray();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);//战士勇士詹皇杰克老王
}
//public void clear()
//清空集合,但是不删除集合
coll.clear();
System.out.println(coll);
boolean i = coll.isEmpty();
System.out.println(i);//true
System.out.println(coll);//[]
}
}