1.ArrayList 类支持能够按需增长的动态数组。本质上,ArrayList就是元素为对象引用的长度可变的数组。
package Collection; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; class ArrayListDemo { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); System.out.println("Initial size of al "+al.size()); al.add("C"); al.add("B"); al.add("A"); al.add("F"); al.add("E"); al.add(1,"B2"); System.out.println("Size of al after addtion: "+al.size()); System.out.println("Contents of al: " +al); al.remove("F"); al.remove("E"); System.out.println("Size of al after deletions: "+al.size()); System.out.println("Contents of al: "+al); Iterator<String> it=al.iterator(); while (it.hasNext()){ String element=it.next(); System.out.print(element+" "); } ListIterator lit=al.listIterator(); while (lit.hasNext()){ String element= (String) lit.next(); lit.set(element + "+"); } ArrayList<Integer> a=new ArrayList<Integer>(); System.out.println("Initial size of a "+a.size()); a.add(1); a.add(2); a.add(3); a.add(4); System.out.println("Size of after addtion: "+a.size()); System.out.println("Contents of a: "+a); //将集合转换成数组:1.为特定操作获取更快的处理速度。2.为方法传递数组,并且方法没有接收集合的重载形式。3.将基于集合的代码集成到不支持集合的遗留代码中 Integer ac[]=new Integer[a.size()]; ac=a.toArray(ac); int sum=0; for (int i:ac){ sum +=i; } System.out.println("Sum is : "+sum); } }2.LinkedList类扩展了AbstractSequentialList类,实现了List,Deque以及Queue接口,并且它还提供了一种链表数据结构。
package Collection; import java.util.LinkedList; class LinkedListDemo { public static void main(String[] args) { LinkedList<String> l1 = new LinkedList<String>(); l1.add("A"); l1.add("J"); l1.add("E"); l1.add("W"); l1.add("C"); l1.add("F"); l1.add(2,"T"); l1.addFirst("O"); l1.addLast("P"); System.out.println("Original contents of l1: "+l1); l1.remove("F"); l1.remove(2); System.out.println("Contents of l1 after deletion: "+l1); l1.removeFirst(); l1.removeLast(); System.out.println("l1 after deleting first and last: "+l1); String val=l1.get(2); l1.set(2,val+" Changed"); System.out.println("After changed l1: "+l1); } }3.HashSet类扩展了AbstractSet类并实现了Set接口,该类用于创建使用哈希表存储元素的集合。
package Collection; /** * hashSet中的元素顺序随机排列,如果需要有序的排列使用TreeSet. */ import java.util.HashSet; class HashSetDemo { public static void main(String[] args) { HashSet<String> hs = new HashSet<String>(); hs.add("hhi"); hs.add("ooo"); hs.add("oioi"); hs.add("ahu"); System.out.println(hs); } }4.TreeSet类扩展了AbstractSet类并实现了NavigableSet接口,用于创建使用树进行存储的组。对象以升序存储,访问和检索速度非常快,这对于存储数据量大的,必须能够快速查找的有序信息来说,TreeSet是极佳的选择。
package Collection; /** * 用于创建使用树存储的元素 */ import java.util.TreeSet; class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts=new TreeSet<String>(); ts.add("A"); ts.add("D"); ts.add("B"); ts.add("Y"); ts.add("VG"); System.out.println(ts); System.out.println(ts.subSet("D","Y")); } }
