How can we implement compare method of comparator class [closed]

╄→гoц情女王★ 提交于 2019-12-25 19:08:04

问题


How can we implement a compare method that compares Employees by their employee Id?

public int compare(Employee emp1, Employee emp2) {
        throw new UnsupportedOperationException("Not supported yet.");
        if(emp1.getEmpid()<emp2.getEmpid())
        {
            return -1;
        }    
        else if(emp1.getEmpid()>emp2.getEmpid())
            return 1;
        else
            return 0;
    }

回答1:


public int compare(Employee emp1, Employee emp2) {
       if(emp1==null || emp1==null ){
             throw new UnsupportedOperationException("Not an Employee instance");
       }
       if(emp1.getEmpid()<emp2.getEmpid()){        
          return -1;
       }    
       else if(emp1.getEmpid()>emp2.getEmpid()){
           return 1;
       }
       return 0;
    }



回答2:


remove throw new UnsupportedOperationException("Not supported yet."); line from the code. It is added by your IDE(I think) and it is unnecessary here.



来源:https://stackoverflow.com/questions/18760391/how-can-we-implement-compare-method-of-comparator-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!