user2371701
user2371701

Reputation: 27

ArrayList methods are not working

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

Answers (6)

ayo
ayo

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

Sameer Shamsudeen
Sameer Shamsudeen

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

Singular1ty
Singular1ty

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

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

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

Mark Bertenshaw
Mark Bertenshaw

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

rgettman
rgettman

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

Related Questions