Error trying to use ArrayList methods (unrecognized symbol)

1

IsimplycannotuseanyArrayListclassmethod(italwaysgivescompilationerror)andIhavenoideawhy.AmImakingasyntaxerror?Ididnotgetanyanswersbysearchingtheinternet.Itookpicturestodemonstrateexactlytheproblem.It'sasifhedoesnotrecognizethe"."

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 execute, so I commented the lines to leave the command prompt leaner. The error was exactly the same on all lines (as shown in the image).

import java.util.ArrayList;

public class ArrayList {

    public static void main (String[] args) {

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

    }
}
    
asked by anonymous 20.01.2017 / 20:56

1 answer

2

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

In addition, you can parameterize ArrayList to ensure that the only type of object that will be inserted in your ArrayList is of type String , thus:

import java.util.ArrayList;

public class ArrayListTest {

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

Another way to resolve this name collision problem, which can be used when you can not change the name of the classes, is to use Fully Qualified name :

public class ArrayList {

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