首页 > 代码库 > Java集合的使用

Java集合的使用

//ArrayList集合的使用		ArrayList arr=new ArrayList();		//添加元素		arr.add(new Object());		arr.add("123");		arr.add("12313");		arr.add(new Exception());		arr.add(new Date());		//修改元素		arr.set(2, "123");		for (Iterator iterator = arr.iterator(); iterator.hasNext();) {			Object object = (Object) iterator.next();			System.out.println(object);		}		System.out.println(arr.size());//集合长度		System.out.println(arr.indexOf("123"));//获得元素的位置		System.out.println(arr.contains("123"));//是否包含		System.out.println(arr);		//排序		//Collections.sort(arr);//对象不能排序		Collections.reverse(arr);		System.out.println(arr);			arr.remove(0);//删除集合中元素		System.out.println(arr);		//清空元素		arr.clear();//清空元素		System.out.println(arr);		System.out.println(arr.isEmpty());//是否为空		People p1 = new People("xxx","x",10);		People p2 = new People("yyy","x",10);		People p3 = new People("zzz","x",10);		//HashMap集合		HashMap hs=new HashMap();		hs.put(1, "qwr");		hs.put(2, new Date());		hs.put(3, p1);		hs.put(3, p2);//重复了键。就会覆盖了		hs.put(4, p3);		System.out.println(((People)hs.get(3)).getName());		System.out.println(hs);		System.out.println(hs.containsKey(1));		System.out.println(hs.containsValue("qwr"));		//通过键遍历所有的值		System.out.println("========================");		Set st=hs.keySet();		for (Object object : st) {			System.out.print(hs.get(object));		}		Iterator it= st.iterator();		while (it.hasNext()) {			Object object = (Object) it.next();			System.out.print(hs.get(object));					}		//获取所有的值		Collection cc= hs.values();		for(Object o : cc){			System.out.println(o);		}		//键值同是获取		Set  kv=hs.entrySet();		for(Object o : kv){			System.out.println(o);		}		System.out.println(hs.size());//长度		hs.remove(1);//删除		hs.clear();//清空		System.out.println(hs.isEmpty());//是否为空		//下面的两个集合和arrlist用法一样		LinkedList lk = new LinkedList();		Vector v = new Vector();		//集合的泛型		ArrayList<People> ap=new ArrayList<People>();		ap.add(new People("wer", "n", 23));		ap.add(new People("wrer", "n", 13));		ap.add(new People("qw", "n", 25));		Iterator  itp=ap.iterator();		while(itp.hasNext()){			System.out.println(((People)itp.next()).getName());		}

  

Java集合的使用