添加新成员“无法从静态上下文中引用的非静态变量”时出现Arraylist问题

时间:2015-05-15 15:48:34

标签: java class arraylist

我正在尝试创建类对象的arraylist。当我将类对象添加到数组列表时,我得到“非静态变量....静态上下文”错误。

我的arraylist:

ArrayList<CookieClass> cookieList = new ArrayList<CookieClass> ();
cookieList.add(new CookieClass("chocolate chip", 20));

我的课程:

class CookieClass
{
     private String cookieName;
     private int cookieNum;

     public CookieClass(String cookie, int num)
     {
         cookieName = cookie;
         cookieNum = num;
     }

}

1 个答案:

答案 0 :(得分:-1)

试试这个......

BroadcastReceiver

输出

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

public class CookieClass {

    private String cookieName;
    private int cookieNum;

    public CookieClass(String cookie, int num) {
        cookieName = cookie;
        cookieNum = num;
    }

    @Override
    public String toString() {
        return "CookieClass{" +
                "cookieName='" + cookieName + '\'' +
                ", cookieNum=" + cookieNum +
                '}';
    }

    public static void main (String[] args){
        List<CookieClass> cookieList = new ArrayList<CookieClass>();
        cookieList.add(new CookieClass("chocolate chip", 20));
        cookieList.add(new CookieClass("Strawberry chip", 30));

        for(CookieClass c: cookieList){
            System.out.println(c);
        }
    }
}