1 import java.util.*; 2 3 public class BasicGeneric { 4 public static void main(String[] args) { 5 List<String> c = new ArrayList<String>(); 6 c.add("aaa"); 7 c.add("bbb"); 8 c.add("ccc"); 9 for(int i=0; i<c.size(); i++) { 10 String s = c.get(i); 11 System.out.println(s); 12 } 13 14 Collection<String> c2 = new HashSet<String>(); 15 c2.add("aaa"); c2.add("bbb"); c2.add("ccc"); 16 for(Iterator<String> it = c2.iterator(); it.hasNext(); ) { 17 String s = it.next(); 18 System.out.println(s); 19 } 20 } 21 } 22 23 class MyName implements Comparable<MyName> { 24 int age; 25 26 public int compareTo(MyName mn) { 27 if(this.age > mn.age) return 1; 28 else if(this.age < mn.age) return -1; 29 else return 0; 30 } 31 }
MyName类实现了Comparable接口,泛型后,只能和MyName进行比较