Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I override compareTo method in a class I wrote to compare Strings stored in the class?
    text
    copied!<p>I wrote a class, MyClass, and each instance has a String "name" field. I want to override the compareTo method so that when called it will compare the two "name" fields of each instance. </p> <p>Here is what I have so far:</p> <pre><code>public class MyClass implements Comparable&lt;MyClass&gt;{ public String name; public int age; public MyClass(String name) { this.name = name; this.age = 0; } public String getName() { return this.name; } @Override public int compareTo(MyClass mc) { return this.name.compareTo(mc.name); } } </code></pre> <p>When I go to add instances of this class into an ordered list container I wrote, they are not added in the order I want, which is alphabetically. The ordered list doesn't seem to be the problem, as I tested it by adding Strings which are added in the correct order.</p> <p>Here is the add() method of the ordered list:</p> <pre><code>public boolean add(E obj) { Node&lt;E&gt; newNode = new Node(obj); Node&lt;E&gt; current = head, previous = null; if (current == null) { // EMPTY list head = tail = newNode; currentSize++; modCounter++; return true; } while (current != null &amp;&amp; ((Comparable&lt;E&gt;) obj).compareTo(current.data) &gt; 0) { previous = current; current = current.next; } if (previous == null) { // One item in list, inserted node must go in FIRST position newNode.next = current; head = newNode; } else if (current == null) { // Inserted node must go at the END of the list previous.next = newNode; tail = newNode; } else { // Inserted node is somewhere in the MIDDLE of the list newNode.next = current; previous.next = newNode; } currentSize++; modCounter++; return true; } </code></pre>
 

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