繁体   English   中英

在不创建新列表的情况下检查不同 class 中的 ArrayList 中是否存在值

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

在过去的几天里,我在使用 ArrayList 时遇到了一些麻烦。 本质上,这是我的 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);
}

在这个 class 中,我还有一个使用 addWaitingForSlowInput 方法的方法,因此播放器被添加到 ArrayList。

然后,在一个单独的 class 中,我通过执行以下操作检查此 ArrayList 是否包含 UUID:

其他 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

问题:当我在上面的 class 中获得 ArrayList 时,它正在创建列表的新实例,删除玩家的 UUID。

这(显然)在我使用 static 时有效,但我宁愿远离 static 滥用。 我能想到的唯一其他选择是设置 Singleton,但还有其他方法吗?

每次调用new chatutil()时,都会创建该 class 的新实例,因此,它不会继承该 class 的任何其他实例的数据。

您可以通过在 main 中定义 class 的 static 实例来解决此问题,例如:

主class

private static ChatUtil CHAT_UTIL;

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

public static ChatUtil getChatUtil(){
    return CHAT_UTIL;
}

然后在你的其他课程中,你可以做这样的事情; 其中MyPlugin是您的主要 class

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

Java 类的命名约定是 PascalCase,所以我在示例中将您的chatUtil class 重命名为ChatUtil

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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