This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing objects  RSS feed

 
Alastair Binner
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to store a list of Objects in a TreeMap.

These objects are called Person and implements comparable.

the constructor is public Person(String firstName, String secondName, String telNo, int age){
//some code
}

there are get and set methods for every vaiable in the constructor.

what should the compareTo() method look like if I want to order Persons by secondName, telNo then firstName?

Thanks
 
Jon Egan
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alastair,

Just a hint, in case this might be a school assignment

Look at the doc for String's "compareTo" method - perhaps your "compareTo()" method could make use of String's method? Or maybe String's "compareToIgnoreCase()", depending on your requirements.

Also, if this is for the "real world", look at the javadoc for the Comparable interface - it recommends implementing compareTo in a manner that is "consistent with equals()", which means that for correctness, you should override the equals() method whenever you define compareTo(). But then, that leads you down another path - when you override equals(), you should always override hashCode().

Post back with a guess if you need another "nudge".

-- Jon
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as comparing on two fields sketch out the logic you would use to sort index cards by names. If last names are different, I would .... If last names are the same I would .... If this doesn't come real naturally, get some code together and show us how it's going.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, you should look at the JavaDocs for the Comparable interface. This will give you the signature for the compare() to method (i.e. the required return type and parameter list). As for the contents of the method, I think the above suggestions are great, so I don't have anything to add.

Layne
 
Alastair Binner
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it that obvious?

Yeah I probably could spend half an hour working it out but if anyone fancies just telling me I would really appreciate it

Cheers
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!