Reputation: 35
Is it possible to find the index of an array within an ArrayList?
The method indexOf
doesn´t seem to work. For instance, for a given list of arrays with size two, this code prints "-1"
List<Integer[]> nodes = new ArrayList<Integer[]>();
nodes.add(new Integer[] {1,1});
System.out.println(nodes.indexOf(new Integer[] {1, 1}));
Upvotes: 3
Views: 1175
Reputation: 2443
No you cannot do that. new Integer[]{1, 1}
is an integer object and your code creates to separate objects of the same.
To do what you want to do,
// You need to save a reference of your array in a variable
Integer[] arr = new Integer[]{1, 1};
// Add it to your list
nodes.add(arr);
// Finally retrieve the index
System.out.println(nodes.indexOf(arr));
When you print out the index of the variable arr
, it will refer to the same integer array object created before.
Upvotes: 0
Reputation: 1355
You need to understand that Java compare by reference rather than by value in this case. The following code is displays the correct solution:
List<Integer[]> nodes = new ArrayList<>();
Integer[] a = new Integer[] {1,1};
nodes.add(a);
System.out.println(nodes.indexOf(a)); //0
System.out.println(a == a); //true
System.out.println(a == new Integer[] {1,1}); //false
System.out.println(Arrays.equals(a, new Integer[]{1, 1})); //true
Ordinary objects for comparison is to use the method equals(). (etc. a.equals(b)) For arrays and some class need static method.
Upvotes: 2
Reputation: 3105
indexOf method "returns the lowest index i such that (o==null ? get(i)==null : o.equals( get(i))), or -1 if there is no such index", as stated in the Java API. And for arrays, array1.equals( array2) is the same as array1 == array2, therefore you get -1 as those two arrays have different references.
Upvotes: 0
Reputation: 32054
The equals()
implementation of the primitive Java array performs a reference equality check. Meaning, they're only considered equal if the references point to the same instance of the array.
You could write your own index-seeking method that uses the Arrays.equals()
static method like so:
List<Integer[]> nodes = new ArrayList<Integer[]>();
nodes.add(new Integer[] {1,1});
Integer[] lookingFor = new Integer[] {1,1};
int index = -1;
for (int i = 0; i < nodes.size(); i++) {
Integer[] array = nodes.get(i);
if (Arrays.equals(lookingFor, array)) {
index = i;
break;
}
}
System.out.println(index); // 0
Upvotes: 6