@Test
public void list(){
Collection coll = new ArrayList();
Collection coll1 = Arrays.asList(1,2,3);
//1.size();返回集合中元素的个数
System.out.println(coll.size());
//2.add(Object obj);向集合中添加元素
coll.add("AA");
coll.add(123);
System.out.println(coll.size());
//3.addAll(Collection colll);将形参colll中包含的所有元素添加到当前集合--->(调用该方法的集合)
coll.addAll(coll1);
System.out.println(coll.size());
//4.isEmpty:判断集合是否为空--返回boolean类型的
System.out.println(coll.isEmpty());
//5.clear();清空集合元素
coll.clear();
System.out.println(coll.isEmpty());
System.out.println(coll.size());
//6.查看集合中的元素
System.out.println(coll1);
}
@Test
public void list1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add("AA");
coll.add(new Date());
//7.contains(Object obj);判断集合中是否包含指定的obj的元素,如果包含返回True,不包含返回false
//注:如果存入的集合中的元素是自定义类型的对象。要求:自定义类需要重写equals方法
//class Person{
// String name;
// int age;
// public Person(String name,int age){
// this.name = name;
// this.age = age;
// }
// }
//coll.add(new Person("小明",23))
//coll.contains(new Person("小明",23))---重写Person的equals方法后,此处返回true;
boolean b = coll.contains(123);//这里的123是integer类型的的(自动装箱),非int类型
System.out.println(b);
//8.containsAll();
System.out.println("8.containsAll()的用法");
System.out.println("查看coll的元素:"+coll);
Collection coll2 = Arrays.asList(123,456,789);
System.out.println("查看coll2的元素:"+coll2);
boolean b1 = coll.containsAll(coll2);
System.out.println("判断coll是否包含coll2:"+b1);
coll.addAll(coll2);
System.out.println("把coll2集合加入到coll中后,再判断coll是否包含coll2:"+coll.containsAll(coll2));
System.out.println("打印出加入coll2后的coll集合元素:"+coll);
//9.retainAll();保留两个集合共同的元素(交集)
System.out.println("9.retainAll()的用法");
coll.retainAll(coll2);
System.out.println(coll);
//10.remove()
System.out.println("10.remove()的用法");
coll.remove(123);
System.out.println(coll);
//11.removeAll(Object obj)
System.out.println("11.removeAll()的用法");
coll.add("AA");
coll.add("BB");
coll.removeAll(coll2);
System.out.println("删除后的coll集合中的元素还剩:"+coll);
//12.equals(Object obj);判断两个集合是否相等
System.out.println("12.equals(Object obj)的用法");
Collection coll3 = new ArrayList();
coll3.add("AA");
coll3.add("BB");
System.out.println("判断coll和coll3两个集合元素是否相等:"+coll.equals(coll3));
//13.toArray(Object obj);将集合转化为数组
System.out.println("13.toArray(Object obj)的用法");
System.out.println("coll集合转化前的元素:"+coll);
Object[] obj = coll.toArray();
for (int i =0;i<obj.length;i++){
System.out.println("打印转化后的数组:"+obj[i]);
}
//14.iterator();返回一个iterator实现类的对象,进而用来遍历集合元素
System.out.println("13.iterator() 的用法");
coll.add(123);
coll.add(456);
Iterator it = coll.iterator();
// System.out.println(it.next());
System.out.println("####");
while (it.hasNext()){
System.out.println(it.next());
}
}