-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 aList
. In doingnew ArrayList[tam]
, you just said that the array hastam
elements, but as the elements are not yet initialized, they arenull
. And in doingelA[i]
you tried to access one of these elementsnull
, so it was not possible to access the methodadd
, hence the error. If you just want a list, doList<Elemento> elA = new ArrayList<>()
and thenelA.add(el)
– hkotsubo
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).
– Michele Bruno Filho
In this case you have to initialize each position of the array with a new list:
elA[i] = new ArrayList<>()
(actually make afor
for all array positions, so no list is null)– hkotsubo
Thanks. I’ll do that. Thanks
– Michele Bruno Filho