Skip to content
Advertisement

Java – changing an arraylist from another class

So, I’ve made a public arraylist that I need to change from another class. shielded is an arraylist, that stores the UUID as a string of every player that has toggled the shield on. This code does not affect the array in class one, but still lets me toggle it just in that class.

After accessing it in Class 3, using if (vars.shielded.contains(otherPlayer.getUniqueId().toString())) {, it always returns false, and no player UUIDs are in the array.

It toggles

Class one:

public class ClassOne {
    
    public ArrayList<String> shielded = new ArrayList<String>();
    
    public void addItem(String item) {
        this.shielded.add(item);
    }
    
    public void removeItem(String item) {
        this.shielded.remove(item);
    }
}

Class Two (Snippet):

ClassOne vars = new ClassOne();

... 

if(vars.global.shielded.contains(p.getUniqueId().toString())) {
    vars.removeItem(p.getUniqueId().toString());
    p.sendMessage("You are NOT in the list");
}
else {
    vars.addItem(p.getUniqueId().toString());
    p.sendMessage("You're in the list.");
}

Advertisement

Answer

Make the ArrayList in ClassOne static.

Is the “global” in “vars.global.shielded.contains…” correct?

if(vars.global.shielded.contains(p.getUniqueId().toString())) {
vars.removeItem(p.getUniqueId().toString());
p.sendMessage("You are NOT in the list");
}

Perhaps you should replace it with following code snippet.

if(vars.shielded.contains(p.getUniqueId().toString())) {
vars.removeItem(p.getUniqueId().toString());
p.sendMessage("You are NOT in the list");
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement