0

假设,我有一个带有卷号和姓名的学生班。我想整理一下卷号。我尝试了以下。这是我的代码:

package CollectionDemo;
import java.util.*;


class student1 implements Comparable<student1>{
    int rollNo;
    String name;

    student1(int rollNo,String name){
        this.rollNo=rollNo;
        this.name=name;
    }
    @Override
    public boolean equals(Object o){
        if((o instanceof student1) && (((student1)o).rollNo == rollNo)){
             return true;
        }
          else
        {
              return false;
        }
    }

    @Override
    public int hashCode(){
        return 1;
    }

    public int compareTo(student1 s) {
        return s.rollNo;
    }

    public String toString(){
        return "["+rollNo+","+name+"]";
    }
}
public class treeSetDemo {
    public static void main(String... a){

        Set<student1> set=new TreeSet<student1>();
        set.add(new student1(102,"Anu"));
        set.add(new student1(101,"Tanu"));
        set.add(new student1(103,"Minu"));

        System.out.println("elements:"+set);

    }
}

o/p: elements:[[102,Anu], [101,Tanu], [103,Minu]]

所以,它没有排序:(如何使它正确。

谢谢你的帮助。

=================================================

感谢你的帮助。以下代码运行良好,但现在我想知道它是如何工作的,如果我注释掉 equals 和 hashcode 方法。

package CollectionDemo;
import java.util.*;


class student1 implements Comparable<student1>{
    int rollNo;
    String name;

    student1(int rollNo,String name){
        this.rollNo=rollNo;
        this.name=name;
    }
   /* @Override
    public boolean equals(Object o){
        if((o instanceof student1) && (((student1)o).rollNo == rollNo)){
             return true;
        }
          else
        {
              return false;
        }
    }

    @Override
    public int hashCode(){
        return 1;
    }
*/
    public int compareTo(student1 s) {
        System.out.println("hello:"+(this.rollNo-s.rollNo));
        return this.rollNo-s.rollNo;
    }

    public String toString(){
        return "["+rollNo+","+name+"]";
    }
}
public class treeSetDemo {
    public static void main(String... a){

        Set<student1> set=new TreeSet<student1>();
        set.add(new student1(102,"Anu"));
        set.add(new student1(101,"Tanu"));
        set.add(new student1(103,"Minu"));

        System.out.println("elements:"+set);

    }
}

OP: 运行: hello:-1 hello:1 元素:[[101,Tanu], [102,Anu], [103,Mnu]] 构建成功(总时间:0 秒)

4

5 回答 5

1

您必须以下列方式更改 compareTo 方法

 public int compareTo(student1 s) {
    if(s.rollNo == this.rollNo){
        return 0;
    }else if(s.rollNo > this.rollNo){
        return -1;
    }else{
        return 1;
    }

}
于 2012-10-30T11:02:17.563 回答
0

我认为这个实现接近推荐:

@Override
public int compareTo(Object other) {
    if(other == null || !(other instanceOf student)){
       throw new IllegalArgumentException();
    }
    student s = (student) other;
    if(this.rollNo > s.rollNo){
         return 1;
    } else if (this.rollNo < s.rollNo){
         return -1;
    } else {
         return 0;
    }
}
于 2012-10-30T11:10:40.470 回答
0

如果您使用的是 Comparable 接口,那么您的 compareTo() 方法应该返回比较不等于方法,谷歌可比较示例。

检查此链接

于 2012-10-30T11:11:05.220 回答
0

在您的compareTo方法中,您只是返回要比较的对象的值。您需要返回调用实例和传递实例的属性的差异。

因此,将您的compareTo方法更改为以下方法:-

@Override
public int compareTo(student1 s) {
    return this.rollNo - s.rollNo;
}

注意: - Onlysign对 很重要Collections.sort,因此您实际上并不需要一个if-else块来返回-1, 0, or 1。只退差价。就这样。


PS: -

您的哈希码实现非常糟糕。它会将每个实例放在同一个存储桶中。

@Override
public int hashCode(){
    return 1;  // All the instances will have the same hashcode.
}

理想情况下,您应该只使用那些属性来计算hashCode您用来比较两个实例的属性,这里是rollNo.

因此,您可以使用一些方程式来计算您的哈希码,而不是简单地返回一个 value 1,同时考虑您的rollNo和 a large prime number

您可以浏览Effective Java - Item#9该主题的更多解释。


现在,您的代码运行良好,让我们转向您的第二个疑问。

equals and hashCode methods are not used when you want to compare two objects that will be used while sorting. We override equals and hashCode methods in order to check whether an instance is equal to another instance later on. So, compareTo method is not concerned with whether you have ocerrided equals ad hashCode method or not. And you can also infer from name as to what the two methods does, and can they be related or not.

Moreover, equals method is defined in Object class, whereas compareTo method is declared in Comparable interface. So, they are not interrelated.

Check the documentation of these methods: - Object#equals, Object#hashCode, and Comparable#compareTo

于 2012-10-30T11:01:53.723 回答
0

-如果您只想根据一个属性进行排序,请使用java.lang.Comparable<T>Intereface,以及Collections.sort(List l)

-但是,如果您的目标是根据多个属性对其进行排序,那么请java.util.Comparator<T>选择Collections.sort(List l, Comparator c).

例如:

import java.util.Comparator;

public class Fruit implements Comparable<Fruit>{

    private String fruitName;
    private String fruitDesc;
    private int quantity;

    public Fruit(String fruitName, String fruitDesc, int quantity) {
        super();
        this.fruitName = fruitName;
        this.fruitDesc = fruitDesc;
        this.quantity = quantity;
    }

    public String getFruitName() {
        return fruitName;
    }
    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }
    public String getFruitDesc() {
        return fruitDesc;
    }
    public void setFruitDesc(String fruitDesc) {
        this.fruitDesc = fruitDesc;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int compareTo(Fruit compareFruit) {

        int compareQuantity = ((Fruit) compareFruit).getQuantity(); 

        //ascending order
        return this.quantity - compareQuantity;

        //descending order
        //return compareQuantity - this.quantity;

    }

    public static Comparator<Fruit> FruitNameComparator 
                          = new Comparator<Fruit>() {

        public int compare(Fruit fruit1, Fruit fruit2) {

          String fruitName1 = fruit1.getFruitName().toUpperCase();
          String fruitName2 = fruit2.getFruitName().toUpperCase();

          //ascending order
          return fruitName1.compareTo(fruitName2);

          //descending order
          //return fruitName2.compareTo(fruitName1);
        }

    };
}
于 2012-10-30T11:04:51.493 回答