Tapani Toivonen
Tapani Toivonen

Reputation: 1

Java; ArrayList<T> indexof

So hi everyone! I've worked with this project to keep a record of a baseball season and I have confront this problem with my ArrayList usage:

. . .

private ArrayList<Team> list1 = new ArrayList<Team>();

Team something = new Team("Somename");
Team somethingelse = new Team("Someothername");

and then I used some setters like:

something.setPoints(1);
somethingelse.setPoints(2);

and then:

list1.add(something);
list1.add(somethingelse);

but here comes the problem:

int help1 = list1.indexOf(something);
System.out.println(help1);

returns -1

but the list contains those objects:

for (Team d: list1) {
      System.out.println(d);
 }

The output is that toString() -method I wrote to the Team class...

and then I tried it with

ArrayList<Integer> list2 = new ArrayList<Integer>();

list2.add(1);

list2.add(2);

int help2 = list2.indexOf(1);
System.out.println(help2);

returns 0

So basically what I am asking is that is that the right way of using indexOf when the list contains objects which have multiple values?

Upvotes: 0

Views: 214

Answers (4)

Miquel
Miquel

Reputation: 15675

If that something object is the same instance all through your example, everything should be fine, since Object.equals is being used, which returns true for the same instance.

If, however, you are creating another object with the same values and all, Object.equals will return false. You need to implement an equals and hashCode method that considers your object fields.

Upvotes: 0

npinti
npinti

Reputation: 52185

As per the Java doc of the indexOf

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.

So you essentially need to override the equals() method with whatever you want to match, for instance:

@Override
public boolean equals(object obj)
{
     if(obj instanceof Team)
     {
          Team t = (Team) obj;
          return t.getName().equals(this.getName());
     }
     return false;

}

This code is untested but it should do what you need. In this case, I consider two teams to be equal if they have the same name.

Upvotes: 1

Morteza Adi
Morteza Adi

Reputation: 2473

you need to override hashcode and equals of Team class!

Upvotes: 2

Apurv
Apurv

Reputation: 3753

You need to override equals method in your Team class. So when you do list1.indexOf(something);, the indexOf method knows how to locate the object something

Upvotes: 3

Related Questions