Home » Java » java – What are the functions of an array of an arrayList?-Exceptionshub

java – What are the functions of an array of an arrayList?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I tried to do:

static boolean newTrait(ArrayList<Integer> population, int[] traits) {
        for(int i = 0; i < 25; i++) {
            for(int j = 0; j < 625; j++) {
                if(traits[j].equals(population[i].get(i))) {
                    return false;
                }
            }
        }
        return true;
    }

The java compiler said that I had an “unresolved compiler issue.”

Can anyone help?

How to&Answers:

[X] operator is for arrays. You don’t have an ArrayList array you just have an ArrayList<> which, although it has “Array” in the name, is not an array and so cannot be accessed with [X]. ArrayList is an object with regular methods.

It’s perfectly valid to have an ArrayList array
e.g.

static boolean newTrait(ArrayList<Integer>[] population, int[] traits)

where each element in the population array IS A ArrayList. In which case you would first need to access the element in the array (via [X]) and then access the elements IN the ArrayList using get()

e.g. get the first element of the array

 ArrayList<Integer> firstList = population[0];

then get the Xth item in the list
e.g.

 firstList.get(x);

Answer:

All simple types (not objects) do not have any methods. In your case neither the array not the int values inside the array have methods.

Fix:

if(traits[j] == population.get(i)) 
{
    return false;
}

This compares an int on the left side with an Integer on the right side. For int the == operator is correct but it would be wrong for Integers. However in this case the compiler does automatically ‘unbox’ the Integer on the right side to int.

Notice that I removed the wrong [i] after population as well. Population is not an array.