简体   繁体   中英

Removing objects from an array(Java)

I have an owner class, which has an array of owned dogs. It looks like this:

public class Owner {
    
    private String ownerName;
    public Dog[] ownedDogs = new Dog[0];
    private int dogCount = -1;
    
    public Owner(String ownerName) {
        this.ownerName = ownerName;
    }
    
    public String getName(){
        return ownerName;
    }
    
    public void assignDog(Dog d) {
        
        Dog[] newOwnedDogs = new Dog[ownedDogs.length + 1];
        for (int i = 0; i < ownedDogs.length; i++) {
            newOwnedDogs[i] = ownedDogs[i];
        }
        ownedDogs = newOwnedDogs;
        
        this.ownedDogs[++dogCount] = d;
        makeOwner(this, d);
    }

   
   private void makeOwner(Owner o, Dog d) { 
        
        if(d.owner !=o) {
            d.owner = o;
        }
    }
    
    public boolean ownerOfDog(Dog d){
        if (d.getOwner() == this){
            return true;
        } else {
            return false;
        }
         
    }
    
    public String toString(){
        return "Name: " + ownerName;
    }

And the dog class looks like this:

public class Dog{
    private String name;
    private String breed;
    private int age;
    private int weight;
    private double tailLength;
    public Owner owner;
    

    public Dog(String name, String breed, int age, int weight) {
            this.name = name;
            this.breed = breed;
            this.age = age;
            this.weight = weight;
            
    }
   
    public String getName() {
        return name;
    }
    
    public String getBreed() {
        return breed;
    }
    
    public void increaseAge() {
        age++;
    }

    public int getAge() {
        return age;
    }

    public int getWeight() {
        return weight;
    }

    public double getTailLength() {
        if (breed.equalsIgnoreCase("dachshund") || breed.equalsIgnoreCase("tax")) {
            return 3.7;
        } else {
            return weight * (age / 10.0);
        }
    }
    
    public Owner getOwner(){
        return owner;
    }
    
    public void setOwner(Owner o) {
        if(this.owner != o) {
            this.owner = o;
            o.assignDog(this);
        }
    }
    
    public String toString() {
        return "Name: " + name + " Breed: " + breed + " Age: " + age + " Weight: " + weight + " Tail length: " + getTailLength() + " owned by: " + owner;
    }
}

And I am trying to create a method to remove a dog from the array, this is what i currently have:

public void removeDog () {
        
        System.out.println("Enter the name of the dog?> ");
        String name = input.nextLine();
        
        Owner o = findOwner(name);
        Dog d = findDog(name);
        
        if(d == null) {
            System.out.println("Error: no such dog");
            
        } else {

            //Code to remove dog from o.ownedDogs
            
        }
            System.out.println(name + " is removed from the register");
    }

Is there a good way to remove objects from an array without manually entering the index of the element? I have seen examples using other data types, but I am a beginner in java, so I am having trouble applying it here.

The problem with using an array is removing an object it actually non-trivial, because you must:

  1. Create a new array of size 1 less than the current one
  2. Find the index of instance
  3. If not found, stop
  4. Copy all elements from the old to the new array up to the index
  5. Copy all elements from the old to the new up array after the index
  6. Swap out the old for the new array in your instance

That is all "too hard" compared with:

public List<Dog> ownedDogs = new ArrayList<>();

then

ownedDogs.remove(d);

You would need to implement equals() (and hashCode() ) in the Dog class.

As a general rule, never use an array when you could use a Collection.


You should probably use Set<Dog> ownedDogs = new HashSet<>(); and make ownedDogs private and provide a getter for it.

From a functional perspective, and assuming that as in your example, the Dog's name is a unique identifier, you would produce a new array by filtering the initial array:

ownedDogs = Arrays.stream(ownedDogs)
.filter(dog -> !dog.name.equals(nameToRemove))
.toArray();

Arrylists would solve this, It could be implemented something like this

public ArrayList<Dog> ownedDogs=new ArrayList<>();

and use

ownedDogs.remove(index);

unlike regular arrays they can have no defined size and once you remove an object from them the index's will all shift accordingly

If you want to remove an element from an array, you should not be using an array. Instead, an ArrayList might fit your needs as you can add and delete dogs very easily.

Given that you use an ArrayList, here is a way you could remove a dog from said list:

for (int i = 0; i < ownedDogs.size(); i++){
   if(d == ownedDogs.get(i)){
      ownedDogs.remove(i);
      break;
   }
}

or:

ownedDogs.remove(d)

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