关于Collection----ArrayList部分使用方法

来源:互联网 发布:知豆可以开多少公里 编辑:程序博客网 时间:2024/06/06 18:04
存储   1数组    2集合
 1数组特点:
  Student[] stu=new Student[20];   stu[0]=new Student();............
 弊端 1:一旦创建不可变      2:数组存放对象的真实个数是不可知的

 3:集合

@Test
public void test2(){
Collection coll=new ArrayList();
coll.add(123);
coll.add(new String("AA"));
coll.add(new Date());
coll.add("BB");
System.out.println();
//Person p = new Person("MM", 23);
coll.add(new Person("MM",23));
//6.contains(Object obj):判断集合是否包含指定obj元素  如果包含就返回true,否则返回false
//判断的依据:根据元素所在的类的equals()方法进行判断
//明确: 如果存入集合的元素是自定义类 要求从写自定义的equals方法
boolean b1 = coll.contains(123);
b1=coll.contains("AA");
System.out.println(b1);
//boolean b2=coll.contains(p);
boolean p = coll.contains(new Person("MM",23));
System.out.println(p);
System.out.println("*****************分隔符********");
//7:containsAll(Collection coll)判断当前集合是否包含coll所有的元素
Collection coll1=new ArrayList();
coll1.add(123);
coll1.add("AA");
boolean b3=coll.containsAll(coll1);
System.out.println(b3);
//8retainAll(Collection coll):要求当前集合和coll共有元素 返回true,否则返回false
coll.retainAll(coll1);
System.out.println(coll);
//9remove(Object obj):
boolean b4=coll.remove("BB");
System.out.println(b4);

}

@Test
public void test1(){

Collection coll=new ArrayList();
//1.size()返回集合中元素(对象)的个数
System.out.println(coll.size());
//2.add(Object odj):像集合添加一个元素
coll.add(123);//int ->Integer自动装箱
coll.add("AA");
coll.add(new Date());
coll.add("BB");
System.out.println(coll.size());
//3.addAll(Collection coll):  将形参coll中包含的所有元素添加到集合中
Collection coll1 = Arrays.asList(1,2,3);
coll.addAll(coll1);
System.out.println(coll.size());
//查看集合元素
System.out.println(coll);
// 4.isEmpty():判断集合是否为空
System.out.println(coll.isEmpty());
5:clear():清空集合元素
coll.clear();
System.out.println(coll.isEmpty());
}