泛型

泛型: 可以把类型当作参数一样传递过来, 在传递过来之前我不明确,
但是在使用的时候我就用明确了。
(早期的 Object 类型可以接收任意的对象类型, 但是在实际的使用中, 会有类型转换的问题。)
也就存在这隐患, 所以 Java 提供了泛型来解决这个安全问题。

泛型通配符《?》 (<>)
任意类型, 如果没有明确, 那么就是 Object 以及任意的 Java 类了
? extends E
向上限定, E 及其子类
? super E
向下限定, E 及其父类

eg:类 ArrayList《E》(是<>)
ArrayList《Student》 s = new ArrayList《Student》(); (是<>)

遍历

for(Student ss : s){
    System.out.println(ss.getName()+"---"+ss.getAge());
}
Iterator<Student> si = s.iterator();
    while(si.hasNext()){
        Student stu = si.next();
        System.out.println(stu.getName()+"---"+stu.getAge());
    }
for(int i =0;i<s.size();i++){
    Student stu = s.get(i);
    System.out.println(stu.getName()+"---"+stu.getAge());
}

类 HashMap《K,V》(是<>)

Map<Student, String> s = new HashMap<Student, String>();
        s.put(new Student("黄", 20),"1");
        s.put(new Student("拉面", 20),"2");
        s.put(new Student("蓝", 20),"3");

        for(Student stu : s.keySet()){
            String ss = s.get(stu);
            System.out.println(stu + "  " + ss);
        }
        for(String s1 : s.values()){
            System.out.println(s1);
        }

TreeMap(Comparator《? super K》 comparator) (<>)

TreeSet用comparator构造的两种方法

 public class TreeSetTest {
//  public static void main(String[] args) {
//      TreeSet<Student> s = new TreeSet<Student>(new Comparator<Student>(){
//
//          @Override
//          public int compare(Student o1, Student o2) {
//          int result = o2.getName().length() - o1.getName().length();
//          result = result == 0 ? o2.getAge() - o1.getAge() : result;
//          return result;
//          }
//      });
//      
//      s.add(new Student("小黄",44));
//      s.add(new Student("小绿lv ",55));
//      s.add(new Student("小绿",56));
//      for(Student ts:s){
//          System.out.println(ts);
//      }
//  }
//} 


    public static void main(String[] args) {
        TreeSet<Student> s = new TreeSet<Student>(new MyComparator());

        s.add(new Student("小黄", 44));
        s.add(new Student("小绿", 55));
        s.add(new Student("小绿", 56));
        for (Student ts : s) {
            System.out.println(ts);
        }
    }
}
class MyComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        int result = o1.getName().length() -o2.getName().length();
        result = result == 0 ?  o1.getAge() - o2.getAge() : result ;
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值