[英]How to cast in the compareTo method to a Generic Class which Implements Comparable?
I have an Arraylist with type Person. 我有一个类型为Person的Arraylist。 Name is a class that I have created. 名称是我创建的类。 In my mainapp I'm creating some Name objects, setting each name-object to a person object and then adding the person objects to an ArrayList. 在我的mainapp中,我正在创建一些Name对象,将每个name-object设置为person对象,然后将person对象添加到ArrayList中。 When I try to sort the list using Collections.sort(), I get a ClassCastException. 当我尝试使用Collections.sort()对列表进行排序时,出现ClassCastException。
I can not see what the problem is. 我看不出是什么问题。
Here is my code so far: 到目前为止,这是我的代码:
public class Person<T> implements Comparable<Person<T>> {
private T name;
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
@Override
public int compareTo(Person<T> o) {
return ((Person<T>) this.getName()).compareTo((Person<T>) o.getName());
}
}
The return value from getName()
has type T
, but you are trying to cast it to Person<T>
. getName()
的返回值类型为T
,但是您尝试将其Person<T>
为Person<T>
。 To fix the problem, you need to compare the names directly without casting: 要解决此问题,您需要直接比较名称而不进行强制转换:
public int compareTo(Person<T> o) {
return this.getName().compareTo(o.getName());
}
Now this will cause another error because the compiler doesn't know if T
has the compareTo()
method. 现在,这将导致另一个错误,因为编译器不知道T
是否具有compareTo()
方法。 To fix that, you need to add a bound to the type T
: 要解决此问题,您需要为T
类型添加一个绑定:
public class Person<T implements Comparable<T>> implements Comparable<Person<T>>
Note: 注意:
To me, this seems like overuse of generics. 在我看来,这似乎过度使用了泛型。 Why should name
be allowed a generic type when String
is the only natural fit? 当String
是唯一自然的匹配方式时,为什么要允许name
为泛型类型? And why do you need a Name
class? 为什么需要一个Name
类? It is likely only a wrapper around a String
so you should just use String
directly. 它可能只是String
的包装,因此您应该直接使用String
。
You are casting this.getName()
, which is of type T
, to type Person<T>
. 您正在将类型为T
this.getName()
转换为Person<T>
。 Ie you are casting a Name to a Person, hence the ClassCastException
("name is not a person"). 也就是说,您正在将名称强制转换为人员,因此ClassCastException
(“名称不是人员”)。
To fix this, please remove the casts and compare the names directly. 要解决此问题,请删除演员表并直接比较名称。 Ignoring null-safety, it would be: 忽略null-safety,它将是:
return getName().compareTo(o.getName());
Note that class Name also needs to implements Comparable<Name>
. 请注意,类Name也需要implements Comparable<Name>
。
Why is your name a type? 为什么你的名字是类型? This looks a bit weird. 这看起来有点奇怪。 Could it be you meant to do something like this: 可能是您打算这样做吗?
public class Person implements Comparable<Person> {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Person other) {
return this.name.compareTo(other.getName());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.