Reputation: 1023
How do you find the index of an int stored inside an ArrayList?
public static void thisClass(int max, int[] queue1, ArrayList<ArrayList<Integer>> aList) {
int[] anArr = Arrays.copyOf(queue1, queue1.length);
Arrays.sort(anArr);
... //sorts ints into groups (ArrayList of ArrayLists)
}
int n = 0;
for (ArrayList<Integer> t : newList) {
String itemS = "";
int total = 0;
for (int index : t) {
int value = index; //isn't returning index of arrayList - its returning the value
if (!itemS.isEmpty()) {
itemS += ", ";
}
itemS += index + ":" + value; //want it to output "element Position : element Value
total += value;
}
}
}
Upvotes: 1
Views: 250
Reputation: 33544
- Use the indexOf()
method to solve this.......
for (ArrayList<Integer> t : newList){
int index = newList.indexOf(t);
System.out.println(index); // Use an array or list to store these
// index if you want.
}
Upvotes: 1
Reputation: 5419
You are using an enhanced for loop
, also referred to as a foreach
loop. In this loop, there is no index variable defined within the loop; it is simply the value within the array/Iterable itself.
To get the index, you'll have to use a traditional for
loop:
ArrayList<Integer> myNumbers = new ArrayList<>();
myNumbers.add(123);
myNumbers.add(456);
myNumbers.add(789);
for(int i = 0; i < myNumbers.size(); i++) {
int value = myNumbers.get(i);
if(value == 789) {
System.out.println("Found 789 at index " + i);
break;
}
}
Upvotes: 3