Collection接口

/*
 * Collection接口特点和方法
 *  Collection集合中的顶层接口,方法,所有的小弟包括子接口,和实现类都具备
 *  
 * 实现类的支持  ArrayList
 */
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
method_6();
}
/*
*  Object[] toArray()
*  集合变成数组
*  这个方法返回的数组,不要进行类型强制转换
*  必须使用带有泛型的,toArray方法
*/
public static void method_6(){
Collection col = new ArrayList();
col.add("abc11");
col.add("abc12"); 
col.add("abc13");
col.add("abc12"); 
col.add("abc14");
 
//调用方法toArray 集合转成数组
Object[] arr = col.toArray();
for(int x = 0 ; x < arr.length ; x++){
System.out.println(arr);
}
 
}
 
 
/*
* int size()
* 返回集合中存储元素的个数
*  java中的三种长度表现形式
*    数组.length 属性
*    字符串.length() 方法
*    集合.size() 方法
*/
public static void method_5(){
Collection col = new ArrayList();
col.add("abc11");
col.add("abc12"); 
col.add("abc13");
col.add("abc12"); 
col.add("abc14");
 
//获取集合的长度
int size = col.size();
System.out.println(size);
}
 
/*
* boolean remove(Object o)
* 移除集合中指定的元素,移除成功返回true
* 集合中有相同元素,移除第一个
*/
public static void method_4(){
Collection col = new ArrayList();
col.add("abc11");
col.add("abc12"); 
col.add("abc13");
col.add("abc12"); 
col.add("abc14");
System.out.println("原始集合 "+ col);
//移除集合中的元素 abc12
boolean b = col.remove("abc12");
System.out.println(b);
System.out.println("移除后集合 "+col);
}
 
/*
* boolean isEmpty()
* 判断集合中有没有元素,如果没有返回true
* 如果方法返回的是true,集合是一个空的
*/
public static void method_3(){
Collection col = new ArrayList();
col.add(1);
//判断集合中是不是有元素
boolean b = col.isEmpty();
System.out.println(b);
}
 
/*
* boolean contains(Object o)
* 判断集合中是不是包含这个元素,如果包含返回true
*/
public static void method_2(){
Collection col = new ArrayList();
col.add("abc11");
col.add("abc12");
col.add("abc13");
col.add("abc14");
System.out.println(col);
//判断字符串 abc12 是不是包含在集合中
boolean b = col.contains("abc12");
System.out.println(b);
}
 
/*
* void clear()
* 清空集合中存储的全部元素,集合还是存在,可以继续使用
*/
public static void method_1(){
Collection col = new ArrayList();
col.add("abc11");
col.add("abc12");
col.add("abc13");
col.add("abc14");
System.out.println(col);
//清空 clear
     col.clear();
System.out.println(col);
}
 
/*
*  boolean add (Object o)
*  将元素存储到集合,参数可以是任意的对象
*/
public static void method(){
//接口指向自己的实现类的对象
Collection col = new ArrayList();
//调用方法add,对称存储到集合
//add方法运行的是 ArrayList实现类重写的
col.add("abc");
col.add(123);
col.add(false); //add (new Boolean (false)) 自动装箱
//输出集合的时候,看到的是集合中存储的元素
//输出方式,目的是为了方便观看,不等于遍历
System.out.println(col);
}
}

 

posted @ 2015-06-22 22:03  G.J.B  阅读(116)  评论(0编辑  收藏  举报