简体   繁体   English

在Java中实现可比较

[英]Implement Comparable in Java

I'm attempting to write a class that deals with locations, such as 00501 Holtsville NY 40.922326 -72.637078, 00544 Holtsville NY 40.922326 -72.637078 . 我正在尝试写一个处理地点的课程,例如00501 Holtsville NY 40.922326 -72.637078, 00544 Holtsville NY 40.922326 -72.637078

I've been able to figure everything out except the Comparable part. 除了Comparable部分之外,我已经能够解决所有问题。 I'm trying to modify the supplied method so that it will return the comparison based on the city name of the place. 我正在尝试修改提供的方法,以便它将根据地点的城市名称返回比较。

public class PostalCodes implements Comparable {
private String city;
private double latitude;
private double longitude;
private String zip;
private String state;

public PostalCodes(String aZip, String aCity, String aState, double aLatitude, double aLongitude)
{
    city = aCity;
    latitude = aLatitude;
    longitude = aLongitude;
    zip = aZip;
    state = aState;
}

void setZip(String aZip)
{
    zip=aZip;
}

void setState(String aState)
{
    state=aState;
}


void setLocation(String aCity)
{
    city = aCity.trim();
}
void setLatitude(double lat)
{
    latitude = lat;
}
void setLongitude(double long1)
{
    longitude = long1;
}
public String getState()
{
    return state;
}
public String getZip()
{
    return zip;
}
public String getLocation()
{
    return city;
}
public double getLatitude()
{
    return latitude;
}
public double getLongitude()
{
return longitude;
}
public String toString()
{
    String result = String.format("%s %s,%s (%1.3f; %1.3f)",zip, city, state, latitude,longitude);
    return result;
}

@Override
public int compareTo(Object arg0) {
    // Confused
    return 0;
}


}

Would it be something like 它会是什么样的

public int compareTo (Object arg0){
    if (arg0>city)
         return True;

Any and all help is much appreciated. 任何和所有的帮助非常感谢。 Please keep it simple, this is the first time i've tried implementing the Comparable thing. 请保持简单,这是我第一次尝试实现可比较的东西。

EDIT: 编辑:

When I try to sort the array in my main as shown below.... 当我尝试在我的主要数组中排序,如下所示....

public class Hmwk { 公共课Hmwk {

public static void main(String[] args) throws IOException {
    URL url = new URL("http://noynaert.net/zipcodes.txt");
    Scanner input=new Scanner (url.openStream());
    int counter =0;
    final int MAX_SIZE=50000;
    PostalCodes[] codesArray= new PostalCodes[50000];
    while (input.hasNextLine() && counter < MAX_SIZE)
    {
        String line=input.nextLine();
        String[] tokens;
        tokens = line.split("\t");
        if (tokens.length != 5)
        {
            continue;
        }
        String zip=tokens[0];
        String city=tokens[1];
        String state=tokens[2];
        double lat=Double.parseDouble(tokens[3]);
        double longy=Double.parseDouble(tokens[4]);
        PostalCodes code=new PostalCodes(zip,city,state,lat,longy);
        codesArray[counter]= code;
        counter++;

    }
    Arrays.sort(codesArray);
    for (int i =0;i<counter; i+=1000)
    {
        System.out.println(codesArray[i].toString());
    }

}

} I get the error 我得到了错误

Exception in thread "main" java.lang.NullPointerException
at PostalCodes.compareTo(PostalCodes.java:69)
at PostalCodes.compareTo(PostalCodes.java:1)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at Hmwk.main(Hmwk.java:37)

What on God's green Earth happened here? 上帝的绿色地球在这里发生了什么?

First, you should really type your Comparable . 首先,你应该键入您的Comparable This way, you have access to the object that you want to compare against without having to cast. 这样,您无需进行强制转换即可访问要比较的对象。

public class PostalCodes implements Comparable<PostalCodes>

Then, when you implement compareTo , you only need to do it on the city field. 然后,当您实现compareTo ,您只需要在city字段上执行它。

public int compareTo(PostalCodes other) {
    return city.compareTo(other.getLocation());
}

You may have to check for null on the object other , or city from both instances. 您可能需要检查null物体other ,或者city的两个实例。

There may be other fields that you want to compare against, but from what you're showing us, two PostalCodes compare based on their city field. 您可能还有其他要比较的字段,但根据您向我们展示的内容,两个PostalCodes根据其city字段进行比较。 The above is the way to do that. 以上是这样做的方法。

If you have more fields you need to compare against, you would add them in. 如果您需要比较更多字段,则可以添加它们。

(You would also be better served by making your getter for city more conventional.) (通过让你的city吸气更传统,你也可以得到更好的服务。)

In your class compareTo method, you can always call compareTo method of String class to compare attributes of type String. 在您的类compareTo方法中,您始终可以调用String类的compareTo方法来比较String类型的属性。 I beleive city name is of type String. 我beleive城市名称是String类型。 For integer use compareTo of Integer class. 对于整数,使用compareTo of Integer类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM