Collection
Collection 集合概述:一种容器,可以同来存储多个数据,它是一个接口,定义的是把所有单列集合的共性方法,这些方法可用于操作所有的单列集合。
Collection接口-->List接口,Set接口
List接口-->ArrayList,ListList实现类...
Set接口-->HashSet,LinkHashSet实现类...
List集合与Set集合的区别:
1、List集合是有序集合,允许存储重复元素,有索引可以用for循环遍历
2、Set集合不允许存储重复元素,无索引,不能用普通for循环遍历,HashSet集合无序,LinkHasSet集合有序
集合和数组都是用来存储的,它们有什么区别:
1、数组的长度是固定的。集合的长度是可变的。
2、数组中存储的是同一类型的元素,可以存储基本数据类型值。集合存储的都是对象。而且对象的类型可以不一致。
ArrayList
//创建集合对象
Collection<String> coll = new ArrayList<>();
// public boolean add(E e):把给定的对象添加到当前集合中
coll.add("赵丽颖");
coll.add("杨幂");
boolean b1 = coll.add("关晓彤");
System.out.println("b1:"+b1);//b1:true
System.out.println(coll);/[赵丽颖, 杨幂, 关晓彤]
//public boolean remove(E e): 把给定的对象在当前集合中删除
boolean b2 = coll.remove("赵丽颖");
System.out.println(b2);//true
// public boolean contains(E e): 判断当前集合中是否包含给定的对象
boolean b4 = coll.contains("张三");
System.out.println(b4);//false
//public boolean isEmpty(): 判断当前集合是否为空
boolean b6 = coll.isEmpty();
System.out.println(b6);//false
// public int size(): 返回集合中元素的个数
int size = coll.size();
System.out.println(size);//2
//public void clear():清空集合中所有的元素
coll.clear();
System.out.println(coll);//[]
System.out.println(coll.isEmpty());//true
LinkedList
//创建LinkedList集合
LinkedList<String> list = new LinkedList<>();
list.add("a");
list.add("b");
list.add("c"
String f = list.pop();//等同list.removeFirst()
System.out.println("被移除的第一个元素:"+f);
String l = list.removeLast();
System.out.println("被移除的最后一个元素:"+l);
//获取集合中第一个元素
String first = list.getFirst();
System.out.println(first);//a
//获取集合中最后一个元素
String last = list.getLast();
System.out.println(last);//c
//在集合第一个位置上插入元素
list.push("d");//等同list.addFirst("d")
System.out.println(list);//[d, a, b, c]
//在集合末尾添加元素
list.add("e");//等同list.addLast("com")
System.out.println(list);//[d, a, b, c, e]
String remove = list.remove(2);
System.out.println("被移除的元素:"+remove);//被移除的元素:b
String set = list.set(4,"E");
System.out.println("被替换的元素:"+set);//被替换的元素:e
int i = list.size();
System.out.println("集合中元素的个数是:"+i);//5
HashSet,LinkHashSet
HashSet<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("b");
set.add("c")
System.out.println(set);//[b, a, c]无序,不允许重复
LinkedHashSet<String> linked = new LinkedHashSet<>();
linked.add("a");
linked.add("b");
linked.add("a");
linked.add("c");
System.out.println(linked);//[a, b, c]有序,不允许重复