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(;
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){

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 )

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();

option 2: make your add(...) method static. this also means your "list" should also be static. both are bad.

Need Your Help

How to call the correct overloaded function at runtime?

c# reflection

How do I call the correct overloaded function given a reference to an object based on the actual type of the object. For example...

Iterating over matches from preg_match_all

php regex foreach preg-match-all

I am trying to figure out the mechanics of this plugin in WordPress.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.