How do I add this to an arraylist within a static method?
I'm learning the ropes with Java and I've hit a snag with ArrayLists. The gist of my program is to take some user input parameters, create a class Foo with those parameters, and then add it to an arraylist. The problem is, it complains that I can't reference a non-static type from a static method. The only examples I can find online deal with adding constants ("Cat", "5.0" etc) to arraylists which doesn't really help me.
I put the gist of my code below. I've moved the arraylist off to its own class Bar and added an add method which just does arraylist.add(foo), if only as a crapshoot to make it work (it doesn't). I omitted the loop but it loops a number of times after the definitions, so the arraylist gets populated.
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
}
}
Edit: Here is Bar explicitly
import java.util.ArrayList;
public class Bar{
private ArrayList list = new ArrayList();
public void add(Foo foo){
list.add(foo);
}
}
If it helps, the object foo isn't changed after creation.
How do I get around this? Thanks in advance for any help.
Without information about Bar, or the actual error it complains about, we can't help much.
I'd presume its because the Bar.add
method isn't static, or Bar
isn't static.
// 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);
}
}
or do you intend "Bar" to be a static list member of something else?
// a class with a static member
public class OtherClass
{
public static List<Foo> Bar = new ArrayList<Foo>();
}
then your code would need a OtherClass.Bar.add(o)
instead of just Bar.add(o);
You have 2 options
option 1: create an instance of Bar and add foo to that instance. This is my preferred option
Bar b=new Bar();
b.add(foo);
option 2: make your add(...) method static. this also means your "list" should also be static. both are bad.
精彩评论