简体   繁体   English

从数组中删除对象(Java)

[英]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.我看过使用其他数据类型的示例,但我是 Java 的初学者,所以在这里应用它时遇到了麻烦。

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创建一个大小比当前数组小 1 的新数组
  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.您需要在Dog类中实现equals() (和hashCode() )。

As a general rule, never use an array when you could use a Collection.作为一般规则,当您可以使用集合时,永远不要使用数组。


You should probably use Set<Dog> ownedDogs = new HashSet<>();您可能应该使用Set<Dog> ownedDogs = new HashSet<>(); and make ownedDogs private and provide a getter for it.并将ownedDogs私有并为其提供吸气剂。

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 Arrylists 会解决这个问题,它可以像这样实现

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.相反,ArrayList 可能适合您的需求,因为您可以非常轻松地添加和删除狗。

Given that you use an ArrayList, here is a way you could remove a dog from said list:鉴于您使用 ArrayList,这里有一种方法可以从所述列表中删除一只狗:

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

or:要么:

ownedDogs.remove(d)

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

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