Home > Net >  Java - changing an arraylist from another class
Java - changing an arraylist from another class

Time:10-27

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.");
}

CodePudding user response:

For me, you are creating a new instance for the ClassOne for each method call.

You can create ONE instance and put it in a static field. This is a good way if you are using this instance in a lot of multiple class. To do it, just use public static ClassOne vars = new ClassOne();.

Also, if you are using in only one class (or need multiple instance of different class), I suggest you to do something like that :

public ClassOne vars; // declare variable

public ClassTwo() {
   vars = new ClassOne(); // create a new instance
}

public void yourMethod() {
   if(vars.contains(myUUID)) {
       // should contains
   } else {
       // should not contains
   }
}

CodePudding user response:

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");
}
  • Related