Practical example List and Arraylist

Asked

Viewed 1,961 times

0

I’m creating a list of Estudantes, but I find myself in the following situation. In point 2 gives me error because it says I have to take the Student inside the List but when I do point 1 is already correct.

Suspostamente the goal is to have the main as the point 2. And within the ArrayList nothing. What do you advise? To do as point 1?

public static void main(String[] args) {
    (1) ArrayList<Estudante> lista = new ArrayList<Estudante>(); //assim dá mas com List e arraylist nao da porque?
    (2) List <Estudante> lista1 = new ArrayList<>();
    
}

even if you do so:

    List<Estudante> lista1 = new ArrayList<Estudante>();

The List make a mistake:

The type List is not Generic; it cannot be parameterized with Arguments Estudante

My student class only has the number and the name:

public class Estudante {
private int numero;
private String nome;

public Estudante(int numero, String nome){
    this.numero = numero;
    this.nome = nome;
}
  • 2
  • @diegofm ai had already understood. But in this example is equal! And does not even give.

  • 2

    No, it’s not the same, no ArrayList of the second example is not being informed the type of data that the list will store.

  • but even if you enter the data type is not possible. I will put an example

  • 2

    As I demonstrated in the answer, what is in the issue does not actually occur. If it is occurring I suggest creating a [mcve] to demonstrate this.

  • 2

    The problem is not in the code shown here, see an example identical to yours, using the answer code of @bigown : http://ideone.com/9ZJiTD

  • 2

    Boy, example 2 has to work, if I were to kick without seeing the full code, I’d say you’re importing List from the wrong library. It has to be java.util...

Show 2 more comments

2 answers

4


Just put the object that will be used in the object construction. You can only omit if the variable type declaration is equal to the object construction:

import java.util.*;

class Main {
    public static void main(String[] args) {
        ArrayList<Estudante> lista = new ArrayList<Estudante>();
        List<Estudante> lista1 = new ArrayList<Estudante>();
        ArrayList<Estudante> lista2 = new ArrayList<>();
    }
}

class Estudante {}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Don’t forget to do the import.

4

Probably the problem is import incorrect. You must be importing the class List graphical user interface package. Just switch:

import java.awt.List;

For:

import java.util.List;

Your code will work normally.

IDEONE

Browser other questions tagged

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