Julien
Julien

Reputation: 237

Check if data is added to array java

I would like to check if the data is added to the array. when the data is inserted into the array i would like to send a messagebox to the user.

what i have now is

public static ArrayList<ModuleData> modules;

public Module()
{
    modules = new ArrayList<ModuleData>();
}

public void addModule(String naamModule, int modulenr, int aantalUren, int weekBegin, int weekEind, String opleiding, int opleidingJaar)
{
    modules.add(new ModuleData(naamModule, modulenr, aantalUren, weekBegin, weekEind, opleiding, opleidingJaar));
}

I was thinking about return true or false if modules.add is succesfull

Upvotes: 0

Views: 264

Answers (2)

alex
alex

Reputation: 11400

ArrayList is a Collection, so modules will return true if it is changed upon insertion (as stated here). If you receive true, something was added.

public void addModule(String naamModule, int modulenr, int aantalUren, int weekBegin, int weekEind, String opleiding, int opleidingJaar){
    boolean dataAdded = false;
    try {
        dataAdded = modules.add(new ModuleData(naamModule, modulenr, aantalUren, weekBegin, weekEind, opleiding, opleidingJaar));
    } catch (Exception e) {
       // handle exception
    }

    if( dataAdded ){
       // notify user about success 
    }
}

Or you can rewrite the addModule() method to return dataAdded and handle the response outside.

Upvotes: 4

Vaandu
Vaandu

Reputation: 4935

public boolean addModule(String naamModule, int modulenr, int aantalUren, int weekBegin, int weekEind, String opleiding, int opleidingJaar)
{
    boolean added = true;
    try {
        modules.add(new ModuleData(naamModule, modulenr, aantalUren, weekBegin, weekEind, opleiding, opleidingJaar));
    } catch (Exception e) {
       added = false;
    }
    return added;
}

Adding logs and handling method inputs will be good too.

Upvotes: 1

Related Questions