![](/img/trans.png)
[英]How to add an object from an ArrayList to another ArrayList in another class
[英]Remove object from 1 arraylist and add to another
我真的希望我能在這里傳達我的意圖:
我有一個名為(“分支”)的 class(我相信它被稱為對象),並且我有 2 個分支實例。
基本上(在我的主要課程中):
private static Branch branch1 = new Branch();
private static Branch branch2 = new Branch();
我知道如何(在基本層面上)添加到分支以及如何從分支 1 中刪除。
(在我的分支 class 文件中):
public void addPet(VirtualPet pet) {
pets.add(pet);
}
public void removePet(String name) {
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getName().equals(name)) {
pets.remove(i);
}
}
}
這些工作正常。 但我正在嘗試從 1 個分支轉移到另一個分支(例如:branch1 到 branch2)。
我想我的 removePet 方法是一樣的,但我想知道如何將該寵物添加到另一個分支? 我知道如何添加一個全新的寵物,但我不確定如何從我要刪除的寵物中提取數據並使用它來添加新寵物。
答案很簡單,return remove item 並添加到另一個branch
// return the pet
public VirtualPet removePet(String name) {
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getName().equals(name)) {
return pets.remove(i); // API https://docs.oracle.com/javase/8/docs/api/java/util/List.html#remove-int-
}
}
return null;
}
// then you can add this to other object
VirtualPet pet = branch1. removePet("something");
if (pet != null) {
branch2.addPet(pet);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.