Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use of of a Comparable object as a parameter to indexof

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried the following simple test.



The output of the above test is



I understand why the second line is producing 3 but i dont understand why the first line is not finding the new an object with title="Croydon".

The API describes the indexof method as one that


Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.


I think the API is saying that if the object is null then it will return the index of the first occurrence of a null object from the list. If it is not null it will return the index of the first occurrence where the passed in object equals method returns trued. Shouldnt the the object created as cities3.indexOf(new Cities("Croydon") equal to the object added previously as cities3.add(new Cities("Croydon")); ?

Thanks

[Edit - changed code tags to quote tags to fix the page width - MB]
 
sachin potu
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try overriding equals and hash code, may be this can help you
 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is CompareTo not used for comparison?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
compareTo() is used for ordering, but equals() is (usually) used to test for equality, and so is what indexOf will be using.

...in fact, the bit from the API documentation that you quote above specifically says that.
 
Arjun Srivastava
Ranch Hand
Posts: 432
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Output:
IndexOf(new Croydon)- 5
IndexOf(city)-3
cities3.contains(new Cities("Croydon"))-true
new Cities("Croydon").equals(new Cities("Croydon"))-true

With overriding equals() ,it will work as "==" and It will see both objects as different.
cities3.contains(new Cities("Croydon"))-false
new Cities("Croydon").equals(new Cities("Croydon"))-false
Hope this helps you.

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. I originally thought that compareTo could be used for checking for equality.
Thanks for clarifying this.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic