我在代码里加了toString方法就可以了。同时将代码的顺序调了一下。要注意代码的可读性,构造方法一般都放在前面。
import java.util.*;
class Employee implements Comparator {
private String name;
private int Salary;
public Employee() {
super();
}
public Employee(String name, int salary) {
super();
this.name = name;
this.Salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
public static Comparator<Employee> Comparesal = new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return (int) (o1.getSalary() - o2.getSalary());
}
};
public static Comparator<Employee> Comparename = new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return (o1.getName().compareTo(o2.getName()));
}
};
public int compare(Object o1, Object o2) {
return 0;
}
//重写toString方法。
public String toString()
{
return this.name;
} //toString方法重载,用来根据需要返回。
public String toString(Object obj) {
if (obj instanceof String)
{
return name;
}
else if (obj instanceof Integer)
{
return Salary+"";
}
else if (obj instanceof Employee)
{
return "["+name+":"+Salary+"]";
}
else
return null;
}
public static void main(String args[]) {
Employee[] emparr = new Employee[3];
emparr[0] = new Employee("Adam", 30000);
emparr[1] = new Employee("John", 40000);
emparr[2] = new Employee("Gates", 50000);
//按照名字排序
Arrays.sort(emparr, Employee.Comparename);
//System.out.println(Arrays.toString(emparr)); //这里会调用Employee类下无参数的toString方法,不要下面的代码也能实现你的要求了
//根据想要返回的内容调用带参数的toString方法。
for (Employee emp : emparr) {
//System.out.println(emp.toString(emp.Salary));
//System.out.println(emp.toString(emp.name));
System.out.println(emp.toString(em));
}
public class Employee implements Comparator<Object> {
private String Name;
private int Salary;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
public Employee() {
super();
}
public static Comparator<Employee> Comparesal = new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return (int) (o1.getSalary() - o2.getSalary());
}
};
public static Comparator<Employee> Comparename = new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
return (o1.getName().compareTo(o2.getName()));
}
};
public int compare(Object o1, Object o2) {
return 0;
}
public Employee(String name, int salary) {
super();
this.Name = name;
this.Salary = salary;
}
public static void main(String args[]) {
Employee[] emparr = new Employee[3];
emparr[0] = new Employee("Adam", 30000);
emparr[1] = new Employee("John", 40000);
emparr[2] = new Employee("Gates", 50000);