Java 泛型 Generic

来源:互联网 发布:蜂蜜和四叶草 知乎 编辑:程序博客网 时间:2024/06/05 19:31
  1. package v13;
  2. import java.util.*;
  3. public class Test {
  4. public static void main(String[] args){
  5. List<</SPAN>Stringc new ArrayList<</SPAN>String>();//采用泛型 使传入的对象类型只能是String
  6. c.add("aaa");
  7. c.add("bbb");
  8. c.add("ccc");
  9. for (int i ;ic.size();i++){
  10. String s c.get(i);
  11. System.out.println(s);
  12. System.out.println(c.get(i));
  13. }
  14.  
  15. Collection<</SPAN>Stringc2 new HashSet<</SPAN>String>();//泛型使用
  16. c2.add("aaa");
  17. c2.add("bbb");
  18. c2.add("ccc");
  19. for (Iterator<</SPAN>Stringit c2.iterator();it.hasNext(); ){
  20. String s it.next();
  21. System.out.println(s);
  22. }
  23. Map<</SPAN>String,Integer> m new HashMap<</SPAN>String,Integer>();//泛型使用,注意参数
  24.  
  25.  
  26. }
  27.  
  28. }
  29.  
  30. class MyName implements Comparable{
  31. int age;
  32. public int compareTo(MyName my){
  33. if (this.age my.agereturn 1;
  34. else if(this.age my.agereturn -1;
  35. else return 0;
  36. }
  37. }
0 0
原创粉丝点击