比较不同类型的物体具有可比性 [英] Comparing different type of Objects with comparable
问题描述
A.java
public class A implements Comparable {
private String id;
private String name;
public A(String a, String b) {
id = a;
name = b;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int compareTo(Object o) {
A a = (A) o;
return id.compareTo(a.getId());
}
}
B.java
public class B implements Comparable {
private String b_id;
private String other;
public B(String a, String b) {
b_id = a;
other = b;
}
public String getBId() {
return b_id;
}
public void setBId(String id) {
this.b_id = id;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
public int compareTo(Object o) {
B b = (B) o;
return b_id.compareTo(b.getId());
}
}
Learn.java
public class Learn {
public static void main(String[] args) {
List<A> listA = new ArrayList<A>();
List<B> listB = new ArrayList<B>();
List<Object> listAll = new ArrayList<Object>();
listA.add(new A("aa", "bb"));
listA.add(new A("ae", "bbn"));
listA.add(new A("dfr", "GSDS"));
listB.add(new B("nm", "re"));
listB.add(new B("asd", "asfa"));
listAll.addAll(listA);
listAll.addAll(listB);
Collections.sort(listAll);
for (Object o : listAll) {
if (o instanceof A)
System.out.println(o.getId);
else if (o instanceof B)
Syatem.out.println(o.getBId);
}
}
}
我得到的错误是在行 Collections.sort(listAll);
它说。
The error i get is at the line Collections.sort(listAll);
It says.
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable
for the arguments (List<Object>). The inferred type Object is not a valid substitute
for the bounded parameter <T extends Comparable<? super T>>
怎么办?其余的逻辑还可以吗?
What to do? Also is the rest of the logic all right?
我要做的是有一个A列表和一个B列表,其中一个属性与id相同;虽然变量名称不一样。即B. $ b中的 id
in A
和 bid
$ b现在我将这两个列表放在ListAll中,并在相同的变量id / bid上对它们进行排序。
我有A和B实现Comparable。
What i am trying to do is have a list of A and list of B with one attribute same as id; though the variable name is not the same. i.e id
in A
and bid
in B.
Now i put both the lists in ListAll and do sort on them on the same variable id/bid.
I have A and B implementing Comparable.
我的listAll是Object类型吗?
and my listAll is of type Object?
我该怎么做?
谢谢。
how do I do it? thanks.
推荐答案
您可以添加公共基类并在那里实现比较,如:
You could add a common base class and implement comparison there, as in:
abstract class AandBComparable implements Comparable {
public int compareTo(Object o) {
AandBComparable ab = (AandBComparable) o;
return getId().compareTo(ab.getId());
}
public abstract String getId();
}
这篇关于比较不同类型的物体具有可比性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!