سؤال

I am trying to make a GUI that has an ArrayList List and it needs to be shared among classes:

public class Selection extends JPanel
{

public static ArrayList<String> List = new ArrayList<String>();

public Selection()
{

//Adding button for user to click.  If clicked, a line of text will be 
//added into ArrayList<String> List

}}  //End of the Selection Classes

This is another classs that I want them to share the same ArrayList

public class Total extends JPanel
{

public static ArrayList<String> List = new ArrayList<String>();

public Total()
{

    //Setting up a button for calculating a sum based on the text 
    //in ArrayList<String> List

 }}  //End of Total Class

I try to do the following:

public Selection(ArrayList<String> List)
public Total(ArrayList<String>  List)

But it gives me error. What should I do in order to one ArrayList to be shared among two or more classes?

لا يوجد حل صحيح

نصائح أخرى

It looks like you may want a singleton. You can Google how to implement it. For instance create an Enum Table with only one enum in which you provide a method to access an arraylist.

Once you have done this. You can safely use it in both your classes.

Hope it helps.

Your approach won't work. Static variables are class variables. So all instances of the Total class will share the same ArrayList, and likewise, all instances of Selection will share the same (reference to) ArrayList, however - instances of Total will refer to a different ArrayList than instances of Selection.

That's a mouthful. But what you need to do is pass the same instance of ArrayList to each class, either through their constructors or through a setter method. Alternately, you could have a static method from a different class which returns the same reference to ArrayList.

The important take-home point is that you misunderstand the meaning of static. Also, what you're asking about is dependency injection. There have been entire frameworks developed to address this problem, the most popular example in Java being Spring framework. Using a framework would be gross overkill for your requirement, but I just thought I'd let you know.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top