binary101
binary101

Reputation: 1023

ArrayList index?

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

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

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

Phil K
Phil K

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

kosa
kosa

Reputation: 66677

You need to use indexOf(object) to get the index.

Assuming you are using greater than java5. Otherwise you need to create a Integer object instead of primitive int.

Enhanced for loop uses iterator internally, so you couldn't get hold of index.

Upvotes: 1

Related Questions