码迷,mamicode.com
首页 > 编程语言 > 详细

Java集合的使用

时间:2016-10-09 09:08:23      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:

//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集合的使用

标签:

原文地址:http://www.cnblogs.com/ivrigo/p/5919484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!