Note that there are some explanatory texts on larger screens.

plurals
  1. POComparing different type of Objects with comparable
    text
    copied!<p><code>A.java</code></p> <pre><code>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()); } } </code></pre> <p><code>B.java</code></p> <pre><code>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()); } } </code></pre> <p><code>Learn.java</code></p> <pre><code>public class Learn { public static void main(String[] args) { List&lt;A&gt; listA = new ArrayList&lt;A&gt;(); List&lt;B&gt; listB = new ArrayList&lt;B&gt;(); List&lt;Object&gt; listAll = new ArrayList&lt;Object&gt;(); 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); } } } </code></pre> <p>The error i get is at the line <code>Collections.sort(listAll);</code> It says.</p> <pre><code>Bound mismatch: The generic method sort(List&lt;T&gt;) of type Collections is not applicable for the arguments (List&lt;Object&gt;). The inferred type Object is not a valid substitute for the bounded parameter &lt;T extends Comparable&lt;? super T&gt;&gt; </code></pre> <p>What to do? Also is the rest of the logic all right?</p> <p>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 <code>id</code> in <code>A</code> and <code>bid</code> 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.</p> <p>and my listAll is of type Object?</p> <p>how do I do it? thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload