### 申明:本帖子中的内容很多地方参考了网上相关资料,个人整理后便于总结回顾。参考帖的链接
Collection接口的常用 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190730185734291.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzU4MjEyMw==,size_16,color_FFFFFF,t_70)
List接口特点 :
1.可以允许重复的对象。
2.可以插入多个null元素。
3.是一个有序容器,保持了每个元素的插入顺序,输出的顺序就是插入的顺序。
4.常用的实现类有 ArrayList、LinkedList 和 Vector。ArrayList 最为流行,它提供了使用索引的随意访问,而 LinkedList 则对于经常需要从 List 中添加或删除元素的场合更为合适。
Set接口的特点:
1.不允许重复对象
2. 无序容器,无法保证每个元素的存储顺序,TreeSet通过 Comparator 或者 Comparable 维护了一个排序顺序。
3. 只允许一个 null 元素
4.Set 接口最流行的几个实现类是 HashSet、LinkedHashSet 以及 TreeSet。最流行的是基于 HashMap 实现的 HashSet;TreeSet 还实现了 SortedSet 接口,因此 TreeSet 是一个根据其 compare() 和 compareTo() 的定义进行排序的有序容器。
add方法的使用 :
Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("itcast");
coll.add("itheima");
coll.add("money");
coll.add("123");
clear方法的使用 :
/*
* Collection接口的方法
* void clear() 清空集合中的所有元素
* 集合容器本身依然存在
*/
public static void function(){
//接口多态的方式调用
Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("bcd");
System.out.println(coll);
coll.clear();
System.out.println(coll);
}
contains 方法的使用 :
/*
* Collection接口方法
* boolean contains(Object o) 判断对象是否存在于集合中,对象存在返回true
* 方法参数是Object类型
*/
private static void function_1() {
Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("itcast");
coll.add("itheima");
coll.add("money");
coll.add("123");
boolean b = coll.contains("itcast");
System.out.println(b);
}
remove 方法的使用 :
/*
* Collection接口方法
* boolean remove(Object o)移除集合中指定的元素
*/
private static void function_3(){
Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("money");
coll.add("money"); //此处插入重复的元素
coll.add("123");
System.out.println(coll);
boolean b = coll.remove("money");
System.out.println(b);
System.out.println(coll);
}
Size 方法的使用 :
/*
* 学习Java中三种长度表现形式
* 数组.length 属性 返回值 int
* 字符串.length() 方法,返回值int
* 集合.size()方法, 返回值int
*/
toArray 方法的使用 :
/* Collection接口方法
* Object[] toArray() 集合中的元素,转成一个数组中的元素, 集合转成数组
* 返回是一个存储对象的数组, 数组存储的数据类型是Object
*/
private static void function_2() {
Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("itcast");
coll.add("itheima");
coll.add("money");
coll.add("123");
Object[] objs = coll.toArray();
for(int i = 0 ; i < objs.length ; i++){
System.out.println(objs[i]);
}
}