教材p448 Example15_4

任务详情

教材p448 Example15_4

  1. list中增加自己学号后三名同学,学号是最后三名的从1号开始加入
  2. 提交运行结果截图
  3. 刻下推送代码到码云

代码

import java.util.*;
class Student implements Comparable {
    int height=0;
    String name;
    Student(String n,int h) {
        name=n;
        height = h;

    }
    public int compareTo(Object b) { // 两个Student对象相等当且仅当二者的height值相等
        Student st=(Student)b;
        return (this.height-st.height);
    }
}
public class Example15_4 {
    public static void main(String args[ ]) {
        List<Student> list = new LinkedList<Student>();
        list.add(new Student("张三",188));
        list.add(new Student("李四",178));
        list.add(new Student("周五",198));
        list.add(new Student("5336",181));
        list.add(new Student("5337",176));
        list.add(new Student("5338",171));
        Iterator<Student> iter=list.iterator();
        System.out.println("排序前,链表中的数据");
        while(iter.hasNext()){
            Student stu=iter.next();
            System.out.println(stu.name+ "身高:"+stu.height);
        }
        Collections.sort(list);
        System.out.println("排序后,链表中的数据");
        iter=list.iterator();
        while(iter.hasNext()){
            Student stu=iter.next();
            System.out.println(stu.name+ "身高:"+stu.height);
        }
        Student zhaoLin = new Student("zhao xiao lin",178);
        int index = Collections.binarySearch(list,zhaoLin,null);
        if(index>=0) {
            System.out.println(zhaoLin.name+"和链表中"+list.get(index).name+"身高相同");
        }
    }
}

运行截图

代码链接

https://gitee.com/yukungbhy/yukun-20155335/blob/fff3c606b15e77e4bc6d3a0a61837f4b38d2454b/20155335/Example11_1.java

posted on 2019-06-04 15:32  俞昆  阅读(76)  评论(0编辑  收藏  举报

导航