Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList indexOf() method  RSS feed

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi There,
I am trying to use an ArrayList of some TestObj(having private String fields lName, fName with getter and setter methods).

Everytime I create a TestObj, I add this new TestObj to ArrayList testList.
say I did something like testList.add(new TestObj("Taylor","Mark");
testList.add(new TestObj("Waugh","Steve")
testList.add(new TestObj("Waugh","Mark")

Now if I want to find the index for a specific TestObj in the testList, say with fields lName="Waugh" and fName = "Mark".....I know that I have to use the indexOf method of the ArrayList, i.e. testList.indexOf(something).....which shall give me the index of the correct object. Here I wanted to know what should be the "something" in testList.indexOf(something) so that I can retrieve the index of the correct TestObj...which in this case should return 2.

Do I have to override any methods? How does ArrayList indexOf() method work in such cases? All the example I find on the internet are for finding the index of straight forward strings or Integer objects. Any response in this regard shall be highly appreciated.

regards,
Rahul
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rahul,

Try overriding "equals" method from "Object" class.

http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html

Regards,
Antany.
 
Ak Rahul
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Antany,
Thanks for the solution. It works fine now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!