In collections, how can I get the index using the indexOf method in the following example
class Fruit{
public String name;
Fruit(String name){
this.name = name;
}
}//end of Fruit
class FruitList{
public static void main(String [] arg5){
List<Fruit> myFruitList = new ArrayList<Fruit>();
Fruit banana = new Fruit("Banana");
//I know how to get the index of this banana
System.out.println("banana index "+myFruitList.indexOf(banana));
//But i'm not sure how can i get the indices for the following objects
myFruitList.add(new Fruit("peach"));
myFruitList.add(new Fruit("orange"));
myFruitList.add(new Fruit("grapes"));
}//end of main
}//end of FruitList
Since the rest of the objects I've added to the ArrayList are unreferenced, I'm not entirely sure how their index can be obtained. Please help, Thanks a lot.
+3
source to share
1 answer
It doesn't matter which reference the object is as long as you override the equals and hashcode methods in the Fruit class. indexOf
, contains
etc. use the method equals(...)
to decide if an object exists inside the collection.
For example, your Fruit class might be like this (I changed yours public String name
to private):
public class Fruit {
private String name;
public Fruit(String name){
this.name = name;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Fruit other = (Fruit) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
Then:
Fruit f = new Fruit("orange");
myFruitList.indexOf(f); // this should return the orange fruit index (would be 1 in your example).
+6
source to share