[英]Converting Arraylist into Observable list without creating a whole new list class?
[英]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.