You say arraylist, but you show ordinary arrays here ?
Anyway, the elements int the arraylist must either be
String, Boolean, Character or numeric (Integer, Float...) for the indexOf to
work, or the you have to have the
Code:
public boolean equals (Object ob)
method implemented in the class that you store in the list
Check this out
Code:
import java.util.*;
/**
* Find index of an object in an arraylist
*/
class SomeClass {
public String name=null;
public int iD=-1;
public SomeClass(String name, int iD) {
this.name=name;
this.iD=iD;
}
public boolean equals(Object ob) {
if (!(ob instanceof SomeClass)) {
return false;
}
SomeClass sC=(SomeClass)ob;
return name.equals(sC.name) && iD == sC.iD;
}
}
public class AList {
ArrayList list=new ArrayList();
public AList() {
SomeClass sC1=new SomeClass("ABC",123);
SomeClass sC2=new SomeClass("DEF",223);
SomeClass sC3=new SomeClass("GHI",323);
SomeClass sC4=new SomeClass("JKL",423);
list.add(sC1);
list.add(sC2);
list.add(sC3);
list.add(sC4);
// this one would manage without the equals method,
// its found by reference (address) value
System.out.println("sC3 index: "+list.indexOf(sC3));
// this one misses (returns -1) without the equals method.
SomeClass sC5=new SomeClass ("GHI",323);
System.out.println("sC5 index: "+list.indexOf(sC5));
}
public static void main(String[] args) {
AList al=new AList();
}
}
Bookmarks