1

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?

4
  • There is a serious issue in public addElement(String input) because it does not define a return type in its signature. Write public void addElement(String input) instead... Commented Aug 6, 2018 at 9:27
  • I would like to know why you think that "obviously ... ArrayList needs to be static". It seems like this whole question is based on a misconception. Commented Aug 6, 2018 at 9:40
  • @KYL3R nope, this us just java 8 diamond operator, you don't need to specify twice, imagine Map<String, List<Map<String,Integer>>> m = new HashMap<String, ArrayList<HashMap<String, Integer> becomes = new HashMap<> Commented Aug 6, 2018 at 10:21
  • thanks, didn't know that :) Commented Aug 6, 2018 at 10:24

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This programme will ask to change chain variable to static. It won't even compile
@DebmalyaBiswas why would it? I compiled it successfully without any problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.