1. Collection 接口常用的方法
- size():返回集合中元素的个数
- add(Object obj):向集合中添加一个元素
- addAll(Colletion coll):将形参coll包含的所有元素添加到当前集合中
- isEmpty():判断这个集合是否为空
- clear():清空集合元素
- contains(Object obj):判断集合中是否包含指定的obj元素
① 判断的依据:根据元素所在类的equals()方法进行判断
②明确:如果存入集合中的元素是自定义的类对象,要去:自定义类要重写equals()方法 - constainsAll(Collection coll):判断当前集合中是否包含coll的所有元素
- rentainAll(Collection coll):求当前集合与coll的共有集合,返回给当前集合
- remove(Object obj):删除集合中obj元素,若删除成功,返回ture否则
- removeAll(Collection coll):从当前集合中删除包含coll的元素
- equals(Object obj):判断集合中的所有元素 是否相同
- hashCode():返回集合的哈希值
- toArray(T[] a):将集合转化为数组
①如有参数,返回数组的运行时类型与指定数组的运行时类型相同。 - iterator():返回一个Iterator接口实现类的对象,进而实现集合的遍历。
- 数组转换为集合:Arrays.asList(数组)
2.demo
public class TestCollection {
@Test
public void testCollection(){
Collection coll = new ArrayList<>();
System.out.println(coll.size());
coll.add(123);
coll.add("AA");
coll.add(new Date());
System.out.println(coll.size());
Collection coll1 = Arrays.asList(1,2,3);
coll.addAll(coll1);
System.out.println(coll.size());
System.out.println(coll.isEmpty());
System.out.println(coll);
coll.clear();
System.out.println(coll.isEmpty());
}
@Test
public void testCollection1() {
Collection coll = new ArrayList<>();
coll.add(123);
coll.add("AA");
coll.add(new Date());
boolean b1 = coll.contains(123);
System.out.println(b1);
Collection coll1 = new ArrayList<>();
coll1.add(123);
coll1.add("AA");
boolean b2 = coll.containsAll(coll1);
System.out.println(b2);
coll1.add("CC");
coll.retainAll(coll1);
System.out.println(coll);
boolean b3 = coll.remove("BB");
System.out.println(b3);
}
@Test
public void testCollection2() {
Collection coll = new ArrayList<>();
coll.add(123);
coll.add("AA");
coll.add(new Date());
Collection coll1 = new ArrayList<>();
coll1.add(123);
coll1.add("AA");
coll.removeAll(coll1);
System.out.println(coll);
System.out.println(coll.equals(coll1));
System.out.println(coll.hashCode());
Object[] obj = coll.toArray();
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
Iterator iterator = coll.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}