Closed. This question needs to be more focused. It is not currently accepting answers. Learn more
想改进这个问题吗更新问题,使其只关注一个问题editing this post
我正在尝试用java对一个对象数组进行排序。我已经创建了例如:

Employee[] hourly = new Employee[];

然后让用户输入nameidhourly pay的值比如问
System.out.println("Please enter employee name, id and hourly pay");

然后将name存储为stingidasinthourly pay的双倍从这里开始,我需要按小时工资按升序对对象数组进行排序。
我想这样做没有比较器或数组列表。

最佳答案

我想这样做没有比较器或数组列表。
您可以让Employee类实现Comparable,然后使用Arrays.sort(employeeArray);对其进行排序

public class Employee implements Comparable<Employee>
{
    //Constructors and other members not shown
    @Override
    public int compareTo(Employee e){
        return (getHourlyPay() - e.getHourlyPay());
    }
}
Arrays.sort(employeeArray);

或者
实现自己的排序方法,根据每个employee对象的小时工资进行排序。排序方式将类似于对整数数组排序。
例如,不是写作。。
if (array[i] < min)  //where array[i] is of type int

你会写。。
if(employee[i].getHourlyPay() < min)

关于java - 如何基于实例变量按升序对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42008908/

10-12 14:14
查看更多