JAVA中集合Collection的常用方法

    技术2022-07-11  84

    JAVA中的Collection的常用方法

    Collection中能存放什么元素: 没有使用“泛型”之前,Collection可以存储Object的所有子类 使用“泛型”之后,Collection中只能存储某个具体的类型Collection中的常用方法: boolean .add(Object o) 向集合中添加元素 int .size() 获取集合中元素的个数 void .clear() 清空集合 boolean .contains(Object o) 判断当前集合中是否包含元素e boolean .remove(Object o) 移除集合中的o元素 boolean .isEmpty() 判断集合中元素个数是否为0 Object[] toArray() 调用这个方法可以把集合转为数组 public class CollectionTest01 { public static void main(String[] args) { //接口无法实例化 //Collection e = new Collection(); //多态 Collection e = new ArrayList(); //向集合中添加元素 e.add(120); //自动装箱 e.add("大威天龙"); e.add(true); e.add(3.14); //获取集合中元素的个数 System.out.println(e.size()); //4 //清空集合 e.clear(); System.out.println(e.size()); //0 e.add(120); e.add("大威天龙"); e.add(true); e.add(3.14); //判断当前集合中是否包含元素e System.out.println(e.contains("大威天龙")); //true //移除集合中的o元素 e.remove(120); System.out.println(e.size()); //3 //判断集合中元素个数是否为0 System.out.println(e.isEmpty()); //false e.clear(); System.out.println(e.isEmpty()); //true e.add(120); e.add("大威天龙"); e.add(true); e.add(3.14); e.add(new Student()); //调用这个方法可以把集合转为数组 Object[] obj = e.toArray(); for (int i = 0; i < obj.length; i++) { System.out.println(obj[i]); } } } class Student{ } //运行结果: 4 0 true 3 false true 120 大威天龙 true 3.14 collection.Student@2f4d3709
    Processed: 0.013, SQL: 9