简体   繁体   中英

Checking if value exists in ArrayList in a different class without creating a new list

I've been having some trouble with ArrayList's over the past few days. Essentially, here's my ArrayList class:

ChatUtil Class

private ArrayList<UUID> waitingForSlowInput = new ArrayList<>();

public ArrayList<UUID> getWaitingForSlowInput(){
    return waitingForSlowInput;
}

public void addWaitingForSlowInput(UUID u){
    getWaitingForSlowInput().add(u);
}

public void removeWaitingForSlowInput(UUID u){
    getWaitingForSlowInput().remove(u);
}

In this class, I also have a method that uses the addWaitingForSlowInput method, so the player gets added to the ArrayList.

Then, in a separate class, I'm checking to see if this ArrayList contains the UUID by doing this:

Other Class

chatUtil = new chatUtil(); // Getting class with ArrayList, but removes everything in List

if(chatUtil.getWaitingForSlowInput().contains(p.getUniqueId())){
// and then I continue the code, but list will never contain the UUID because it's empty

The problem: When I'm getting the ArrayList in the class above, it's creating a new instance of the list, removing the player's UUID.

This (obviously) works when I use static, but I'd rather stay away from static abuse. The only other option I could think of would be to set up a Singleton, but is there any other way to do this?

Everytime you call new chatutil() , you're creating a new instance of that class, and therefore, it doesn't carry over the data from any other instance of that class.

You can solve this by defining a static instance of the class in your main, something like:

Main class

private static ChatUtil CHAT_UTIL;

public void onEnable(){
    CHAT_UTIL = new ChatUtil();
}

public static ChatUtil getChatUtil(){
    return CHAT_UTIL;
}

Then in your other classes, you could do something like this; where MyPlugin is your main class

MyPlugin.getChatUtil().getWaitingForSlowInput(); //...etc...

Java naming conventions for classes is PascalCase so I've renamed your chatUtil class to ChatUtil in the example.

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