简体   繁体   中英

Remove object from 1 arraylist and add to another

I'm really hoping I can convey my intentions here:

I have a class called ("Branch") (I believe it is called an Object) and I have 2 instances of branches.

Basically (in my main class):

    private static Branch branch1 = new Branch();
    private static Branch branch2 = new Branch();

I know how to (on a basic level) add to a branch and how to remove from branch1.

(in my Branch class file):

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

These work fine. But I'm trying to do a transfer from 1 branch to another branch (ex: branch1 to branch2).

I figure my removePet method would be the same, but I'm wondering how do I add that pet to the other branch? I know how to add a completely new pet, but I'm not sure how to pull the data from the pet I'm deleting and use that to add the new pet.

The answer is simple, return remove the item and add to the other 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);
}

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