因此,下面的代码应该打印名称,但相反,我得到以下结果 com.flight.Passenger@659e0bfdAs ,根据我的理解,应该覆盖toString方法,如果我错了请纠正我,如果我是对的,请帮助我覆盖toString方法。
非常感谢您的快速回复,但我仍然有以下问题:
由于我获得了成功的结果,但有没有办法可以打印像Bob,Reeta等参考变量的名称?
package com.flight;
import java.util.Arrays;
public class Passenger implements Comparable {
private int memberLevel;
private int memberDays;
public void setLevel(int memberLevel, int memberDays)
{
this.memberLevel = memberLevel;
this.memberDays = memberDays;
}
public int compareTo(Object o)
{
Passenger p = (Passenger) o;
if(memberLevel> p.memberLevel)
return -1; //negative comes first
else if(memberLevel< p.memberLevel)
return 1; // positive comes afterwards
else {
if(memberDays> p.memberDays)
return -1;
else if(memberDays< p.memberDays)
return 1;
else
return 0;
}
}
public static void main (String[] args)
{
Passenger Bob = new Passenger();
Passenger Reeta = new Passenger();
Passenger Mannat = new Passenger();
Passenger Asses = new Passenger();
Bob.setLevel(1,40);
Reeta.setLevel(1,55);
Mannat.setLevel(2,50);
Asses.setLevel(1,95);
Passenger[] pa = {Bob,Reeta,Mannat, Asses};
//Arrays.sort(pa);
for(Passenger pb : pa)
System.out.println(pb);
}
}
答案 0 :(得分:2)
@Override
public String toString() {
return this. memberLevel + " " + this. memberDays;
}