java - How can I override compareTo method in a class I wrote to compare Strings stored in the class? -
i wrote class, myclass, , each instance has string "name" field. want override compareto method when called compare 2 "name" fields of each instance.
here have far:
public class myclass implements comparable<myclass>{ 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); } }
when go add instances of class ordered list container wrote, not added in order want, alphabetically. ordered list doesn't seem problem, tested adding strings added in correct order.
here add() method of ordered list:
public boolean add(e obj) { node<e> newnode = new node(obj); node<e> current = head, previous = null; if (current == null) { // empty list head = tail = newnode; currentsize++; modcounter++; return true; } while (current != null && ((comparable<e>) obj).compareto(current.data) > 0) { previous = current; current = current.next; } if (previous == null) { // 1 item in list, inserted node must go in first position newnode.next = current; head = newnode; } else if (current == null) { // inserted node must go @ end of list previous.next = newnode; tail = newnode; } else { // inserted node somewhere in middle of list newnode.next = current; previous.next = newnode; } currentsize++; modcounter++; return true; }
you've answered question, 1 thing have know alphabetizing strings case matters. if you're strictly comparing without care case should either upcase or downcase both strings:
return this.name.tolowercase().compareto(mc.name.tolowercase());
otherwise "bravo"
comes before "alpha"
due case.
Comments
Post a Comment