package com;
import java.util.*;
public class testAll {
public static void main(String[] args) {
//多态创建只能使用父亲的方法(例如:lingkedlist无法使用头尾插入的操作)
Collection collection=new Vector();
Collection collection1=new Stack();
Collection collection2=new ArrayList();
Collection collection3=new LinkedList();
//这也是多态创建
List list=new LinkedList();
List list1=new ArrayList();
List list2=new Vector();
List list3=new Stack();
//这也是多态创建
Vector vector=new Stack();
ArrayList arrayList=new ArrayList();
LinkedList linkedList=new LinkedList();
Vector vector1=new Vector();
Stack stack=new Stack();
vector.add(2);
//------------------------------------------------------------
//以下是Collection的常见方法
collection.add(1);
collection.add("A");
collection.add("A");
//添加vector中所有元素
collection.addAll(vector);
//打印所有元素
System.out.println("All elements:"+collection.toString());
//返回集合的hashcode
System.out.println("hashcode: "+collection.hashCode());
//集合中是否存在1元素
System.out.println("是否存在1:"+collection.contains(1));
//包含关系 collection({1,"A","A"})是否包含collection1(空集)
System.out.println(collection.containsAll(collection));
//包含关系 collection1(空集)是否包含collection({1,"A","A"})
System.out.println(collection1.containsAll(collection));
//判空和大小
System.out.println(collection.isEmpty()+" "+collection.size());
System.out.println(collection.isEmpty()+" "+collection.size());
//删除第一个出现的指定元素
collection.remove("A");
System.out.println(collection.isEmpty()+" "+collection.size());
collection.remove("A");
System.out.println(collection.isEmpty()+" "+collection.size());
System.out.println(collection.toString());
collection2.add(1);
collection2.add(2);
//删除与collection2的交集,通俗的说就是删掉collection2中含有的元素
collection.removeAll(collection2);
System.out.println(collection.toString());
//下面演示转换成固定大小的数组
Object[] objects=new Object[collection.size()];
System.out.println("1:");
for (Object object : objects) {
System.out.println(object);
}
//第一种:直接接收
objects=collection.toArray();
//第二种,直接传数组引用
collection.toArray(objects);
System.out.println("2:");
for (Object object : objects) {
System.out.println(object);
}
//------------------------------------------------------------
}
}
Collection接口的常用方法演示
猜你喜欢
转载自blog.csdn.net/BOWWOB/article/details/113578123
今日推荐
周排行