Vasu Mistry
Vasu Mistry

Reputation: 841

How to create individual list for different objects in Java?

What I'm trying to achieve - have a list that is not shared by all the objects i.e. have a unique list for each objects created from a class, something similar to the below code which obviously results in an error because the ArrayList needs to be static.

public class Foo{
   public ArrayList<String> chain = new ArrayList<>();
   public addElement(String input){
        this.chain.add(input);
   }
}
public printList(){
  for(String s : this.chain){
     System.out.println(s);
  }
}
public static void main(){
  Foo x = new Foo();
  Foo y = new Foo();

  x.addElement("abc");
  x.addElement("pqr"); 

  y.addElement("lmn");
  y.addElement("rty");

  x.printList(); //print abc pqr
  y.printList(); //print lmn rty
}

Is there a way to achieve the above outputs?

Upvotes: 1

Views: 100

Answers (1)

Worthless
Worthless

Reputation: 521

Your brackets are all over the place, you miss function return types and their names and calls don't match, moreso your main doesn't follow the normal pattern. In other words it could use some help.

public class Foo
{
public ArrayList<String> chain = new ArrayList<>();


public void addElement( String input )
{
    this.chain.add( input );
}


public void printList()
{
    for( String s : this.chain )
    {
        System.out.println( s );
    }
}


public static void main(String args[])
{
    Foo x = new Foo();
    Foo y = new Foo();

    x.addElement( "abc" );
    x.addElement( "pqr" );

    y.addElement( "lmn" );
    y.addElement( "rty" );

    x.printList(); //print abc pqr
    y.printList(); //print lmn rty
}
}

This should work, from my understanding of what you want. You might wanna initialize ArrayList in constructor - but thats your choice.

Upvotes: 0

Related Questions