Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java for each loop expects object as type while it contains an integer array

Tags:

java

arraylist

I got a beginner's Java question.

I am filling an ArrayList like this:

   private ArrayList getDuplicatesIndexes(char[] letters) {
        ArrayList<int[]> duplicatesIndexes = new ArrayList<int[]>();

        for(int i = 0; i < letters.length; i++ ) {

            for(int j = 0; j < letters.length; j++) {
                System.out.println("compare this");
                System.out.println(letters[i]);
                System.out.println("with this:");
                System.out.println(letters[j]);
                if(letters[i] == letters[j] && i != j) {
                    System.out.println("match!");
                    int[] indexes = new int[2];
                    indexes[0] = i;
                    indexes[1] = j;
                    duplicatesIndexes.add(indexes);
                }
            }
        }

        return duplicatesIndexes;
    }

I want to loop through it like this:

private void checkForSingularLetters(ArrayList duplicatesIndexes, char[] letters) {
        for(int[] indexes : duplicatesIndexes ){
            System.out.println(indexes[0]);
            ...
        }


}

I cant wrap my mind about why the foreach loop is expecting an object while im sure its filled with int[]

Maybe someone could explain it to me. Thanks.

like image 554
Sjaak Rusma Avatar asked May 15 '26 16:05

Sjaak Rusma


2 Answers

You are using the raw form of ArrayList in your method checkForSingularLetters, so that means that Object is expected when iterating. After all, a raw ArrayList could contain anything.

Use the generic form of ArrayList in your method parameter:

private void checkForSingularLetters(ArrayList<int[]> duplicatesIndexes, char[] letters) 
like image 58
rgettman Avatar answered May 17 '26 08:05

rgettman


You have an untyped ArrayList which contains Object by default - try extending the method signature by ArrayList<int[]> duplicatesIndexes,

like image 33
Smutje Avatar answered May 17 '26 08:05

Smutje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!