【问题标题】:How do I add this to an arraylist within a static method?如何将其添加到静态方法中的数组列表中?
【发布时间】:2011-05-20 01:27:14
【问题描述】:

我正在学习 Java 的诀窍,但我遇到了 ArrayLists 的障碍。我的程序的要点是获取一些用户输入参数,使用这些参数创建一个类 Foo,然后将其添加到数组列表中。问题是,它抱怨我不能从静态方法中引用非静态类型。我可以在网上找到的唯一示例涉及向数组列表添加常量(“Cat”、“5.0”等),这对我没有帮助。

我把我的代码的要点放在下面。我已经将 arraylist 移到它自己的类 Bar 中,并添加了一个 add 方法,该方法只执行 arraylist.add(foo),如果只是作为使其工作的废话(它没有)。我省略了循环,但它在定义之后循环了很多次,所以数组列表被填充了。

public class MainClass{

public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int a, b;

a = scanner.nextint();
b = scanner.nextint();

Foo foo = new Foo(a, b);
Bar.add(foo); //Complains here
}
}

编辑:这里是 Bar 明确

import java.util.ArrayList;
public class Bar{
private ArrayList list = new ArrayList();

public void add(Foo foo){
    list.add(foo);
}
}

如果有帮助,对象 foo 在创建后不会更改。

我该如何解决这个问题?提前感谢您的帮助。

【问题讨论】:

  • 为什么不显示所有不起作用的代码
  • 是的,您的 gist 缺少 Bar 的声明和/或错误,所以它不是一个很好的 gist跨度>
  • 已编辑;错误和我说的差不多; “不能从静态上下文中引用非静态方法 add(java.lang.Object)”
  • 如果您的列表只包含一种类型的对象,您也应该考虑使用泛型,并将其声明为private List<Foo> list = new ArrayList<Foo>();
  • 这说明了为什么您应该始终准确地引用错误消息。您最初说“它抱怨我无法从静态方法引用非静态类型”,但后来您说错误是“无法从静态上下文引用非静态方法 add(java.lang.Object)” .非静态类型和非静态方法是有区别的。

标签: java methods static arraylist


【解决方案1】:

你有两个选择

选项 1:创建 Bar 的实例并将 foo 添加到该实例。这是我的首选

Bar b=new Bar();
b.add(foo);

选项 2:将 add(...) 方法设为静态。这也意味着您的“列表”也应该是静态的。两者都不好。

【讨论】:

  • 我也可以试试这个。谢谢。
【解决方案2】:

如果没有关于 Bar 的信息,或者它所抱怨的实际错误,我们也无能为力。

我推测是因为Bar.add 方法不是静态的,或者Bar 不是静态的。

// a class with a public static method that encapsulates a static list
public class Bar
{
    static List<Foo> innerlist = new ArrayList<Foo>();

    public static void add( Foo o )
    {
        innerList.add(o);
    }
}

或者您是否打算将“Bar”作为其他东西的静态列表成员?

// a class with a static member
public class OtherClass
{
     public static List<Foo> Bar = new ArrayList<Foo>();
}

那么您的代码将需要 OtherClass.Bar.add(o) 而不仅仅是 Bar.add(o);

【讨论】:

  • 这里是酒吧;你是对的,它不是静态的。 public class Bar{ private Arraylist list = new Arraylist(); public void add(Object O){ this.add(O);}}
  • 你要么需要创建Bar 的实例,并在你的主方法中使用它,要么你需要在你的栏类上声明add 方法是静态的,并使其@ 987654328@也是静态的。
猜你喜欢
  • 2014-08-13
  • 1970-01-01
  • 2014-08-11
  • 2015-07-13
  • 2014-03-09
  • 2014-11-05
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
相关资源
最近更新 更多