集合Collection是一个接口,它定义的是所有单列集合中共性的方法,所有单列集合都可以使用共性的方法,没有带索引的方法。
Collection有两个子类接口List、Set。
List接口特点:
1.有序的集合
2.允许重复存储的元素
3.有索引,可以使用普通的for循环遍历
List有三个具体实现类:
Vector集合 ArrayList集合 LinkedList集合
Set接口特点:
1.不允许存储重复元素
2.没有有索引,不能使用普通的for循环遍历
List有三个具体实现类:
TreeSet集合 HashSet集合 LinkedHashSet集合(其中LinkedHashSet是有序的)
Collection集合的方法有:
1.add
2.remove
3.contains查找指定元素,返回true或false
4.isEmpty判断是否为空
5.size
6.toArray转换成数组
7.clear清空集合元素
public static void main(String[] args) {
Collection<String> strs = new ArrayList<>();
//1.add
strs.add("赵");
strs.add("钱");
strs.add("孙");
strs.add("李");
strs.add("周");
strs.add("吴");
strs.add("郑");
strs.add("王");
System.out.println(strs);
System.out.println("===================");
//2.remove
strs.remove(7);
System.out.println(strs);
System.out.println("===================");
strs.remove("王");
System.out.println(strs);
System.out.println("===================");
//3.contains
System.out.println("++" + strs.contains("王"));
System.out.println("===================");
System.out.println(strs.contains("李"));
System.out.println("===================");
//4.isEmpty
System.out.println(strs.isEmpty());
System.out.println("===================");
//5.size
System.out.println(strs.size());
System.out.println("===================");
//6.toArray
Object[] array = strs.toArray();
for (Object o : array) {
System.out.println(o);
}
System.out.println("===================");
//7.clear
strs.clear();
System.out.println(strs.isEmpty());
}
另:集合Collections工具类的Collections.shuffle(List<?> list)能随机打乱集合中元素顺序。