Error trying to use Arraylist methods (symbol not recognized)

Asked

Viewed 457 times

1

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

I just can’t use any method of the Arraylist class (always gives compilation error) and I have no idea why. Am I making some syntax error? I didn’t get any answers searching the internet. I put photos to demonstrate exactly the problem. It’s like he doesn’t recognize the "."

The commented lines are because I was going to test the methods of the class (I’m still learning to program), but they all gave error when I tried to run, so I commented the lines to make the command prompt leaner. The error was exactly the same on all lines (the one shown in the image).

import java.util.ArrayList;

public class ArrayList {

    public static void main (String[] args) {

        ArrayList cores = new ArrayList();
        cores.add("Branco");

    }
}
  • 1

    Add the code in text instead of image, as it hinders anyone who helps you test the code. Read that

1 answer

2


This error is occurring because you have named your class as ArrayList. Thus, the method one tries to evoke is a method of its class ArrayList called add(String s) which does not exist, rather than evoking the class method java.util.ArrayList. Change your class name to something like ArrayListTest and that will solve the problem.

In addition, you can parameterize the ArrayList to ensure that the only type of object that will be inserted into its ArrayList be the type String, being like this:

import java.util.ArrayList;

public class ArrayListTest {

    public static void main(String[] args) {
        ArrayList<String> cores = new ArrayList<>();
        cores.add("branco");
    }
}

Another way to solve this name collision problem, which can be used when you cannot change the class name, is to use the Fully Qualified name:

public class ArrayList {

    public static void main(String[] args) {
        java.util.ArrayList<String> cores = new java.util.ArrayList<>();
        cores.add("branco");
    }
}

Browser other questions tagged

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