ArrayList methods are not working

百般思念 提交于 2019-12-18 09:34:28

问题


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.


回答1:


You have created your own ArrayList class and aren't using the built-in Java class. You haven't defined add.




回答2:


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.




回答3:


The answer is very simple. Just change your class name ArrayList to something else, because ArrayList is a default class in Java.




回答4:


ublic 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 ArrayList Class package




回答5:


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");

?




回答6:


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>();


来源:https://stackoverflow.com/questions/16491870/arraylist-methods-are-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!