简体   繁体   English

分配-制作泛型类并实现Comparable(Java)

[英]Assignment - Making a Generic Class and implements Comparable(Java)

I have to make a prog using Java generics, and implement Comparable. 我必须使用Java泛型制作一个编,并实现Comparable。 The code should basically compare 3 peoples age and tell you true or false. 该代码基本上应该比较3个人的年龄并告诉您是对还是错。

We must include the "int age" variable in our class. 我们必须在类中包含“ int age”变量。

This is what I have done: 这是我所做的:

@SuppressWarnings("rawtypes")
public class Person implements Comparable<Person>{ 

    int age; 

    //He said you should have ("int age"), but I dont know how to do this without using generics?

    public Person(int age) 
    {
        this.age = age; 
    }

    public int compareTo(Person o) {
            return compareTo(o); 

    }


}

And my Comparing class: 我的比较班:

public class OrderedTrio<T> {

    @SuppressWarnings("unused")
    public static void main(String[] args) 
    {
        //Create Person object
        Person personA = new Person(10); 
        Person personB = new Person(20);
        Person personC = new Person(30); 

        System.out.println(allEqual(personA, personB, personC)); 

        //Create Employee object 
    }

    //All Equal Method: Returns true if all 3 items are equal according to their equals method
    public static boolean allEqual(Person personA, Person personB, Person personC)
    {
        if(personA.compareTo(personB) ==0 && personB.compareTo(personC)==0)     //If A=B, B=C then A=C
            return true; 
        else
            return false; 
    }
    //Sort Method: Orders items

    //ToString Method: Output format: Item1, 2, 3

}

When I run these I get this error: Exception in thread "main" java.lang.StackOverflowError 当我运行这些命令时,出现以下错误:线程“ main”中的异常java.lang.StackOverflowError

I think the error is in return compareTo(o) , but I dont understand how to compare my CURRENT object, with the one being passed in. 我认为错误是返回compareTo(o) ,但是我不明白如何将当前对象与传入的对象进行比较。

I also don't know what to use the "int age" variable for, it wont let me compare an int with the Person Object. 我也不知道该如何使用“ int age”变量,它不能让我将int与Person Object进行比较。

Yes this will result in stack overflow. 是的,这将导致堆栈溢出。 You have infinite recursion in your compareTo function, calling itself over and over. 您的compareTo函数中具有无限递归,一遍又一遍地调用自身。

The compareTo function is supposed to return an int that represents your "value" you want to give to this object in comparison to the passed in object. compareTo函数应该返回一个int,该int表示与传递的对象相比,您要赋予此对象的“值”。 So you say you want to compare a person based on age, compareTo should simply return an int based on the age variable, something like the following 因此,您说您想根据年龄比较一个人,compareTo应该只根据年龄变量返回一个int,如下所示

compareTo(Person o){
    //i'm younger
    if (this.age < o.age)
         return -1;
    //i'm older
    if (this.age > o.age)
         return 1;
 //same age   
 return 0;
}

Now, when you compare two persons via PersonA.compareTo(PersonB) it should return a value indicated the PersonA is less than (-1) same as (0) or greater than (1) PersonB 现在,当您通过PersonA.compareTo(PersonB)比较两个人时,它应该返回一个值,指示PersonA小于(-1)与(0)相同或大于(1)PersonB

this solution is meant to show the general concept of what your trying to do, a more efficient solution would be to just subtract the values from eachother and return that, something like 该解决方案旨在说明您尝试执行的操作的一般概念,一种更有效的解决方案是从彼此取值并将其返回,例如

return age - o.age;

You made your method compareTo recursive but without any possibility to stop this recursion. 您已将方法设为compareTo递归,但没有任何可能停止此递归。 Inside your compareTo method you have to add some condition which will return int , for example: compareTo方法内部,您必须添加一些条件,该条件将返回int ,例如:

public int compareTo(Person o) {
    return (age - o.age);
}

This way you will compare two Person instances based on their age field. 这样,您将根据两个Person实例的age字段进行比较。 You can't compare to instances of a class like whole instances - it's not the role of compareTo . 您不能将类的实例与整个实例进行比较-它不是compareTo的角色。 You have to make some assumptions on what condition you will compare those two instances and here, as you have only one field age , good assumption will be to compare to Person based on their age. 您必须对要比较这两个实例的条件做出一些假设,在这里,由于您只有一个田地age ,因此,最好根据其年龄与Person进行比较。

public int compareTo(Person o) {
        return age-o.age; // youngest first
        // return o.age-age; // oldest first   
}

Also, read the documentation about compareTo . 另外,请阅读有关compareTo的文档。 You appear not doing. 您似乎没有做。

Well this is the cause of your stack overflow error: 好吧,这是您的堆栈溢出错误的原因:

public int compareTo(Person o) {
        return compareTo(o); 

}

compareTo, calls compareTo, calls compareTo, calls.... you get the idea, it never finishes and returns. compareTo,调用compareTo,调用compareTo,调用...。您得到了这个主意,它永远不会完成并返回。

A simple comparison of the integer values would be something like 简单比较整数值将类似于

    public int compareTo(Person o) {
            return age - o.age; //or to be java-y :
//Integer.valueOf(age).compareTo(Integer.valueOf(o.age)); 
//or Integer.signum(age - o.age);
//I personally don't trust people to use compareTo properly and not look for 1 or -1 :)

    }

Edit: also, suppressing rawtype warning is pretty naughty. 编辑:而且,抑制rawtype警告是很顽皮的。 Raw Type is the exact opposite of generic. 原始类型与通用类型完全相反。 If you're getting raw type warnings, you're writing explicitly non-generic code! 如果收到原始类型警告,那么您正在编写显式的非泛型代码!

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

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