java---Collection

来源:互联网 发布:java 前景 知乎 编辑:程序博客网 时间:2024/06/10 02:06
1.存储对象可以考虑:(1)数组(2)集合
 * 2.数组存储对象:
 (1)特点:Student[] stu = new Student[20]; stu[0] = new Student();......
 (2)弊端:1.一旦创建,其长度不可变。2.数组存放对象的真实个数是不可知的

 3.集合:

@Test
public void test(){
Collection coll = new ArrayList();
//1.size():返回集合中元素(对象)的个数
System.out.println(coll.size()); 
//2.add(Object obj):往集合里添加一个元素
coll.add(123);//int->Ingeter自动装箱
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);
System.out.println(coll.size());
//4.isRmpty():判断集合里面是否为空
System.out.println(coll.isEmpty());
//5.clear():清空数据
coll.clear();
System.out.println(coll.isEmpty());
}

@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);//int->Ingeter自动装箱
coll.add("AA");
coll.add(new Date());
coll.add("BB");
// Person person = new Person("MM",23);
// coll.add(person);
coll.add(new Person("MM",23));
System.out.println(coll);
//6.contains(Object obj):判断集合中是否包含指定的obj元素,如果包含返回true,返回false
//判断的依据,根据元素所在的类的equals()方法进行判断
//明确:如果存入集合中的元素是自定义类的对象,要求自定义类要重写equals()方法
boolean b1 = coll.contains(123);
System.out.println(b1);
boolean b2 = coll.contains("AA");
System.out.println(b2);
boolean b3 = coll.contains(new Person("MM",23));
System.out.println(b3);
//7.containsAll(Collection coll):判断当前集合是否包含coll中所有的元素
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(new String("AA"));
boolean b4 = coll.containsAll(coll1);
System.out.println(b4);
//8.retainAll(Collection coll):求当前集合与coll的共有的元素,返回给当前集合
coll.retainAll(coll1);
System.out.println(coll);
//9.remove(Object obj)
boolean b5 = coll.remove("BB");
System.out.println(b5);


}


原创粉丝点击