一、首先看一下集合的框架图:
由于collection也继承了Iterator和comparable接口,因此我们可以使用Iterator来遍历元素,也可以通过自定义compareTo函数来重新编写自己的排序。
二、代码
1、List
package testCollection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class testList { public static void main(String[] args){ List list = new ArrayList(); list.add("test1"); list.add("test2"); list.add("test3"); System.out.println("out by for!"); for(Object o : list){ System.out.println(o); } System.out.println("out by iterator!"); Iterator iterator = list.iterator(); while(iterator.hasNext()){ String element = (String)iterator.next(); System.out.println(element); } } }
运行结果:
out by for! test1 test2 test3 out by iterator! test1 test2 test3
2、Set,如果遇到重复的元素,不会添加
package testCollection; import java.util.HashSet; import java.util.Set; public class testSet { public static void main(String[] args){ Set set = new HashSet();//使用set一般都是用hashset,这个会快一些 set.add("test1"); set.add("test2"); if(set.add("test2")){ System.out.println("add successful"); }else{ System.out.println("add failed"); } } }
运行结果:
add failed
3、Map
package testCollection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class testMap { public static void main(String[] args){ Map map = new HashMap(); map.put(1, "test1"); map.put(2, "test2"); System.out.println("size "+map.size()); System.out.println(map.get(1)); Set keys = map.keySet(); for(Object key : keys){ System.out.println(key); } map.remove(2); System.out.println("size "+map.size()); } }
运行结果:
size 2 test1 1 2 size 1
4、自定义排序函数
person类,继承Comparable接口,重载compareTo函数
package testCollection; public class Person implements Comparable{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name,int age){ this.name = name; this.age = age; } @Override public int compareTo(Object person) throws ClassCastException { if(!(person instanceof Person)){ throw new ClassCastException("A Person perspected!"); } int age = ((Person)person).getAge(); return this.age-age; } }
测试类
package testCollection; import java.util.Arrays; public class testComparable { public static void main(String[] args){ Person[] persons = new Person[4]; persons[0] = new Person("test1",18); persons[1] = new Person("test2",20); persons[2] = new Person("test3",15); persons[3] = new Person("test4",19); System.out.println("before sorting!"); for(Person p : persons){ System.out.println("name: "+p.getName()+" age: "+p.getAge()); } System.out.println("after sorting!"); Arrays.sort(persons); for(Person p : persons){ System.out.println("name: "+p.getName()+" age: "+p.getAge()); } } }
运行结果:
before sorting! name: test1 age: 18 name: test2 age: 20 name: test3 age: 15 name: test4 age: 19 after sorting! name: test3 age: 15 name: test1 age: 18 name: test4 age: 19 name: test2 age: 20