简体   繁体   中英

add object to arrayList in the constructor

Part of a separate class file for "Bericht"-objects (dutch for messages, contains a string and two dates) :

private ArrayList<Bericht> lijst = new ArrayList<>(); //
//constructor for a new object:
    public Bericht(String bericht, Date startDag, Date eindDag) {
        this.bericht = bericht;
        this.startDag = startDag;
        this.eindDag = eindDag;
       // System.out.println(""+lijst.size())// prints always a "0"
        lijst.add(this);
       // System.out.println(""+lijst.size())//is always one

    }

Somewhere in my main method i create new objects from this class:

 Bericht message = new Bericht(berichtVak.getText(), calendar1.getDate(), calendar2.getDate());
 message.printBerichten(berichtTextArea); //this method prints the String from each Bericht- object in the textarea 

the method "printberichten" iterates the ArrayList and prints all messages

   public void printBerichten(JTextArea jta) {
        StringBuffer bfr = new StringBuffer();
        for (Bericht msg : lijst) {
            bfr.append(msg.getBericht()); //this getter method returns the string
        }
        jta.setText(bfr.toString());
    }

getBericht getter method:

   public String getBericht() {
    return bericht;
}

So if i make a new object, all my previous objects should be displayed in the textArea, but it seems that i only create one instance of my class.

Before and After the command "lijst.add(this)" i added a System.out.println to check the size from the Arraylist and one returns always a 0 and the other a "1".

From your expectation, you need lijst to be static:

private static ArrayList<Bericht> lijst = new ArrayList<>(); //

Optionally printBerichten could be static as well since it does not access any member variables:

public static void printBerichten(JTextArea jta) {

By making lijst static each instance of Bericht will be added to the single list when it is constructed. When lijist was not static, each instance of Bericht would have its own list and only the single instance would be added to that list.

make lijst static:

private ArrayList<Bericht> lijst = new ArrayList<>(); //
    public Bericht(String bericht, Date startDag, Date eindDag) {
        this.bericht = bericht;
        this.startDag = startDag;
        this.eindDag = eindDag;
       // System.out.println(""+lijst.size())
        lijst.add(this);
       // System.out.println(""+lijst.size())

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM