Java集合框架之_Collection接口

来源:互联网 发布:树莓派 nginx 编辑:程序博客网 时间:2024/05/24 11:13
 1.存储对象可以考虑  ①数组  ②集合
 2.数组存储对象的特点的弊端  ①一旦创建其长度不可变  ②真实的存放数组的个数是不可知的
 3.集合类:Java中的集合类主要由Map接口和Collection接口派生而来。其中Collection接口有两个常用的子接口,既List接口

 和Set接口。所以经常说Java集合框架有三大类接口构成(Map接口、List接口和Set接口)

以下将简单介绍Collection接口常用的方法:



/** * 集合的常用方法 */@Testpublic void testCollection1() {Collection coll = new ArrayList();//1.size() 返回集合中元素的个数System.out.println(coll.size());//0//2.add(Object obj) 向集合中添加一个元素 ,默认是从集合的末尾添加coll.add(123);coll.add("黄渤");coll.add(new Date());coll.add(true);System.out.println(coll.size());//4//3.addAll(Collection coll) 将形参coll中包含的所有元素添加到集合中 Collection coll1 = Arrays.asList(1,2,3,4);coll.addAll(coll1);System.out.println(coll.size());//8//4.isEmpty() 判断当前集合是否为空System.out.println(coll.isEmpty());//false//5.clear() 清空当前集合coll.clear();System.out.println(coll.isEmpty());//true}@Testpublic void testCollection2() {Collection coll = new ArrayList();coll.add(123);coll.add(new String("刘德华"));coll.add(new Date());coll.add(new Person("MM", 18));//添加一个匿名Person对象//6.contains(Object obj)判断集合中是否包含obj元素,包含则返回true,反之,返回false//★此方法判断的依据是根据元素所在的类的equals()方法来进行判断的//如果元素存入的是自定义类的对象,要求:自定义类中重写equals()方法!!!boolean b1 = coll.contains(new String("刘德华"));//如果Person类中没有重写equals()方法的话,此处的b1就是false:重写,则为trueb1 = coll.contains(new Person("MM", 18));System.out.println(coll);System.out.println(b1);//7.containsAll(Collection coll)判断当前集合中是否包含coll中的所有元素Collection co = new ArrayList();co.add(123);co.add("刘德华");co.add(456);boolean b3 = coll.containsAll(co);/*NumberFormat f = NumberFormat.getCurrencyInstance();System.out.println(f.format(123.6));*/System.out.println("#"+b3);//8.retainAll(Collection coll)求当前集合与coll共有的元素,并返回给当前集合coll.retainAll(co);System.out.println(coll);//123, 刘德华//9.remove(Object obj)删除集合中的obj元素,若删除成功返回true,反之返回falseboolean b4 = coll.remove("BB");System.out.println(b4);//false}@Testpublic void testCollection3() {Collection coll = new ArrayList();coll.add(123);coll.add("范冰冰");coll.add(new Date());//coll.add(new Person());Collection co = new ArrayList();co.add(123);co.add("范冰冰");//10.removeAll(Collection coll) 从当前集合中删除包含coll的元素//coll.removeAll(co);System.out.println(coll);//11.equals(Object obj)判断当前集合是否内容一致Collection coo = new ArrayList();coo.add(123);coo.add("范冰冰");boolean heh = co.equals(coo);System.out.println(heh);//true//12.hashCode()根据一定的算法,将当前集合转何为hasCode值int i = coll.hashCode();System.out.println("hashCode为:"+i);System.out.println();//13.toArray() 将集合转换为数组Object[] obj = coll.toArray();for (int j = 0; j < obj.length; j++) {System.out.println(obj[j]);}//14.iterator() 返回一个Iterator接口实现类的对象,进而实现集合的遍历Iterator ite = coll.iterator();while (ite.hasNext()) {Object object = (Object) ite.next();System.out.println("迭代器遍历:"+object);}}


原创粉丝点击