我一直在使用可比较的类来运行并正确比较,但是当我尝试打印出值时,它会给我内存地址。我知道这可以通过toString
方法修复,但我不确定如何去做。这是我的代码:
import java.io.*;
import java.util.*;
import java.lang.Object;
public class StreetAddress implements Comparable<StreetAddress>
{
protected int num;
protected String stName;
public StreetAddress(int n, String s){
num = n;
stName = s;
}
public int getNum(){
// returns the street number
return num;
}
public String getName(){
// returns the street name
return stName;
}
public int compareTo(StreetAddress street) throws ClassCastException{
// exception prevents crash if an address is not compared to
// another address
int compareName = this.stName.compareTo(street.stName);
int compareNum = this.num - street.num;
if (compareName < 0){
// first address comes after compared address
return compareName;
}
else if (compareName == 0){ // same address name
if (compareNum < 0){
System.out.println(this.num + "" + this.stName + ", " + street.num + "" + street.stName);
return compareName;
}
else{
System.out.println("");
return compareName;
}
}
else{
// first address comes before compared address
return compareName;
}
}
public static void main(String args[])
{
StreetAddress add1 = new StreetAddress(7864, "cartesian road");
StreetAddress add2 = new StreetAddress(5141, "cartesian road");
StreetAddress add3 = new StreetAddress(1664, "n kings street");
StreetAddress add4 = new StreetAddress(9753, "pioneer parkway");
StreetAddress add5 = new StreetAddress(3643, "starry avenue");
add1.compareTo(add2);
add4.compareTo(add1);
add3.compareTo(add3);
add2.compareTo(add5);
}
}
答案 0 :(得分:5)
简单:
@Override
public String toString() {
return String.format("%d %s", num, stName);
}
@Override
注释不是必需的,但绝对是好的做法。请注意,String.format("%d %s", num, stName)
会生成"[num] [street]"
形式的字符串。如果你想在将来做出改变,我发现String.format
比字符串连接提供了更大的灵活性。
答案 1 :(得分:2)
@Override
public String toString() {
return "StreetAddress: num= " + num + ", stName=" + stName ;
}