标签:
//构造一个空的ArrayList,指定存放的是String类型的数据 ArrayList<String> list = new ArrayList<String>(); //Java中的集合不可以添加基本数据类型,必须是引用数据类型;如果要添加基本数据类型,可以使用包装类 list.add("aaa"); // 可以增加重复的元素 list.add("aaa"); list.add("bbb"); //add()是继承Collection的方法;add(index,element)是 List 的方法 list.add(2, "ccc"); //打印整个ArrayList System.out.println(list); //遍历各个元素并打印 for(int i=0; i<list.size();i++){ System.out.print(list.get(i) + " "); } System.out.println("\r\n====================================");
//通过index修改该位置的元素 list.set(0, "aa"); System.out.println("After reset, the list is: "+list); System.out.println("====================================");
output:
After reset, the list is: [aa, aaa, ccc, bbb]
====================================
//由 ArrayList 转为 Array,转化后的数据类型是Object Object[] array = list.toArray(); for(Object elem : array){ System.out.print(elem + " "); } System.out.println("\r\nThe lenght of the array is: " + array.length); System.out.println("====================================");
output:
aa aaa ccc bbb
The lenght of the array is: 4
====================================
//删除元素,可以传入下标,也可以传入元素 String removed = list.remove(0); System.out.println("The removed element is: "+removed); System.out.println(list); boolean removed2 = list.remove("aaa"); System.out.println(removed2); System.out.println(list); System.out.println("====================================");
//判断集合是否包含某个元素 System.out.println("list contains aaa? : "+list.contains("aaa")); //判断集合是否为空 System.out.println("list is empty? : "+list.isEmpty()); //获得第一个元素 System.out.println("The fisrt element is: " + list.get(0)); System.out.println("====================================");
//清空整个集合 list.clear(); System.out.println("Afer clear, the list is: "+list); System.out.println("====================================");
//遍历集合各个元素:方法1 for(int i=0; i<list.size();i++){ System.out.print(list.get(i) + " "); } //遍历集合各个元素:方法2 for(String el: list){ System.out.print(el + " "); } //遍历集合各个元素:方法3 Iterator<String> iterator = list.iterator(); while(iterator.hasNext()){ String el = iterator.next(); System.out.println(el); }
标签:
原文地址:http://www.cnblogs.com/tomweng/p/4240980.html