Reputation: 27
I am learning about Java and I'm stuck with this ArrayList
problem: the compiler give me error when I try to use simple methods, like add
. Here is the code:
public class ArrayList {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Value A");
list.add("Value B");
list.add("Value C");
}
}
The method is defined in the Javadoc.
It should be really simple to do it, but I really don't know what I'm doing wrong here.
Upvotes: 0
Views: 10266
Reputation: 17
public class ArrayList {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Value A");
list.add("Value B");
list.add("Value C");
}
}
Your className is ArrayList
. Try to change the name and import the ArrayList
class' package.
Upvotes: 0
Reputation: 6107
The answer is very simple. Just change your class name ArrayList
to something else, because ArrayList
is a default class in Java.
Upvotes: 0
Reputation: 2615
ArrayLists have to be initialized differently to standard arrays.
What you want is something like this:
ArrayList<Object> list = new ArrayList<Object>();
list.add(Object o);
Remember that nearly everything in Java is an Object
.
So you can do:
ArrayList<String>...
ArrayList<Integer>...
But the most powerful feature of ArrayLists, and the reason I use them, is when you start making your own classes - for instance, in game development, a common class people make is a Sprite -- you could create an ArrayList of all sprites, such as below:
public class Sprite {}....
ArrayList<Sprite> spriteList = new ArrayList<Sprite>();
Upvotes: -2
Reputation: 18148
Change your code to
java.util.ArrayList list = new java.util.ArrayList();
This will tell the compiler that you want the predefined ArrayList, not your newly defined ArrayList.
Upvotes: 5
Reputation: 5689
Why are you creating a new class called ArrayList? Surely you want to do something like:
ArrayList<String> list = new ArrayList<String>();
list.add("Value A");
list.add("Value B");
list.add("Value C");
?
Upvotes: -2
Reputation: 178263
You have created your own ArrayList
class and aren't using the built-in Java class. You haven't defined add
.
Upvotes: 24