How to pass a List (initialized as an ArrayList) to a method in Java?

时间:2016-12-02 04:57:23

标签: java

I am trying to pass the following List to a method but I am not sure of what parameter to use. When I pass it as a List, it appears empty. Can you please tell what I am doing wrong?

List<String> list1 = new ArrayList();
list.add("b");
list.add("c");

doStuff(list1);


public void doStuff(List<String> list1){
       //This outputs 0, even though I added two values to the list
       System.out.println(list.size());

}

3 个答案:

答案 0 :(得分:2)

You added strings to list, but you are passing list1, not list.

答案 1 :(得分:2)

If this code compiles

public void doStuff(List<String> list1){
       System.out.println(list.size());  // this is NOT the parameter passed in

}

then it must mean that list is a field in your class

so when you do

list.add("b");
list.add("c");

you are adding to this field object, not list1 which is being passed.

Try

List<String> list1 = new ArrayList();
list1.add("b");   // list1
list1.add("c");   // list1

doStuff(list1);


public void doStuff(List<String> list1){
       // should print 2
       System.out.println(list1.size());  // list1

}

答案 2 :(得分:0)

public static void main(String[] args)
    {
        List<String> list1 = new ArrayList();
        list1.add("b");
        list1.add("c");
        doStuff(list1);



    }
    public static void doStuff(List<String> list1){
           //This outputs 0, even though I added two values to the list
           System.out.println(list1.size());

    }