Error adding to a List in JAVA

Asked

Viewed 55 times

-1

I am trying to add a value to a list but am getting the following error:

Cannot invoke "java.util.List.add(Object)" because "[]" is null

The code is this:

static void montaEl(int tam, Elemento el) {
    int i = 0;
    List <Elemento> elA[];   
    elA = new ArrayList[tam];
    elA[i].add(el);
    imprimePares(elA, 9); }
  • When using [], vc actually created an array, in which each element is a List. In doing new ArrayList[tam], you just said that the array has tam elements, but as the elements are not yet initialized, they are null. And in doing elA[i] you tried to access one of these elements null, so it was not possible to access the method add, hence the error. If you just want a list, do List<Elemento> elA = new ArrayList<>() and then elA.add(el)

  • I get it. It’s just that when I do that, I have another problem. The method printPares cannot be changed, this is imposed by the teacher, only that there passes from giving another error "incompatible types: List<Element> cannot be converted to List<Element>[]". printPares was passed as follows: Static void imprimePares(List<Elemento>vet[], int k). If I could change, I would put Static void imprimePares(List<Element>vet, int k).

  • In this case you have to initialize each position of the array with a new list: elA[i] = new ArrayList<>() (actually make a for for all array positions, so no list is null)

  • Thanks. I’ll do that. Thanks

1 answer

-1

Try using this example to get where you want, in solving your add problem in the list:

import java.util.ArrayList;
import java.util.List;

public class ListAddExamples {

    public static void main(String[] args) {

        List<String> vowels = new ArrayList<>();

        vowels.add("A"); // [A]
        vowels.add("E"); // [A, E]
        vowels.add("U"); // [A, E, U]

        System.out.println(vowels); // [A, E, U]

        vowels.add(2, "I"); // [A, E, I, U]
        vowels.add(3, "O"); // [A, E, I, O, U]

        System.out.println(vowels); // [A, E, I, O, U]
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.