为什么即使填充列表后列表中也没有元素?

时间:2016-10-24 06:21:28

标签: java arraylist

package collectionwaliclass;

import java.util.ArrayList;
import java.util.List;

public class ArraylistWaliClass {

    public static List<String> list= new ArrayList<>() ;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //list= ;
    ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass();
                //adding the element to the existing list 
                int counter=0;
                /*while(counter++<10)
                {
                    arraylistWaliClass.addElement("new element"+counter, list);
                }*/
                //traversing the list in the arryaList
                list.forEach((x)->
                {
                    System.out.println(x);

                System.out.println("uff");
                });

                //deleting the list from the arraylist


    }
    public void addElement(String string, List<String> list)
    {
        list.add(string);
    }

}

2 个答案:

答案 0 :(得分:0)

由于范围定义,您只需向参数

添加元素
List<String> list

in

  public void addElement(String string, List<String> list)
    {
        list.add(string);
    }

答案 1 :(得分:0)

如果您只是取消注释while循环,它的工作正常:

输出:

new element1
new element2
new element3
new element4
new element5
new element6
new element7
new element8
new element9
new element10

代码:

package collectionwaliclass;

import java.util.ArrayList;
import java.util.List;

public class ArraylistWaliClass  {

    public static List<String> list= new ArrayList<>() ;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //list= ;
        ArraylistWaliClass arraylistWaliClass= new ArraylistWaliClass();
        //adding the element to the existing list 
        int counter=0;
        while(counter++<10)
        {
            arraylistWaliClass.addElement("new element"+counter, list);
        }
        //traversing the list in the arryaList
        list.forEach((x)->
        {
            System.out.println(x);
        });

        //deleting the list from the arraylist
    }

    public void addElement(String string, List<String> list)
    {
        list.add(string);
    }

}