关于list接口和set接口的示例应用

package ch;

public class Employee implements Comparable<Object> {
//生成名字和薪水两个对象。
    private double salsry;
    private String name;
//对其进行初始化
    public Employee(String name, double salsry) {
        super();
        this.name = name;
        this.salsry = salsry;
    }
//生成get和set方法
    public double getSalsry() {
        return salsry;
    }

    public void setSalsry(double salsry) {
        this.salsry = salsry;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
//进行重写和比较
    @Override
    public int compareTo(Object p) {
        // TODO Auto-generated method stub
        Employee p1=(Employee)p;
        if(this.salsry>p1.salsry)
            return 1;
        else if(this.salsry<p1.salsry)
            return -1;
        else
            return 0;
    }
    
}
package ch;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class Test1 {

    public static void main(String[] args) {
        //定义一个Employee类型的泛型
        Set<Employee> set=new  TreeSet<Employee>();
        Employee p1 =new Employee("张三",8000);
        Employee p2 =new Employee("李四",6000);
        Employee p3 =new Employee("王五",5600);
        Employee p4 =new Employee("马六",7500);
        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p4);
        //利用for--each遍历
        for(Employee e:set)
        {
            System.out.println(e.getName()+":"+e.getSalsry());
        }
        System.out.println("--------------------------------");
        //利用iterator迭代器
        Iterator<Employee> iterator=set.iterator()    ;
        while(iterator.hasNext()){
            Employee p=iterator.next();
            System.out.println(p.getName()+":"+p.getSalsry());
        }
    }
}
JAVA作业(160页12题)

 

posted @ 2017-10-30 16:22  木木困  阅读(317)  评论(0编辑  收藏  举报