【问题标题】:remove an object from an ArrayList从 ArrayList 中移除一个对象
【发布时间】:2023-04-06 07:38:02
【问题描述】:

这里是 java 新手,我无法理解数组。我需要从ArrayList 中删除一个项目,我不知道如何实际编码。我的程序读取一个.csv 文件,从主类传递一个字符串到第二个类,一旦在第二个类中,我需要搜索数组列表并删除该字符串,如果找到它并返回true,表示它已被删除。任何帮助表示赞赏。

二等

public class PersonLogImpl {

private boolean remove;
private boolean isLicenseUnique;
private boolean add;
private final ArrayList<Person> person;

public PersonLogImpl() {
    this.person = new ArrayList<>();
}


public ArrayList<Person> getPersonLog(){
    return Person;
}

public boolean add(Person obj){  //add person object to ordered list 
   person.add(obj);

   return add;
}

public boolean remove (String license){ //remove person with specific license from list

    if(person.remove(person.equals(add))){
            remove = true;
    }
   return remove;
}

编辑: 人物类

public class Person{
private String licenseNumber;

public Person(){

}

public Person(String licenseNumber){
    this.licenseNumber = licenseNumber;
}

public String getLicenseNumber(){
    return licenseNumber;
}

public void setLicenseNumber(String licenseNumber){
    this.licenseNumber = licenseNumber;
}

@Override
public int hashCode(){
    int hash = 7;
    return hash;
}

@Override
public boolean equals(Object obj){
    if (this == obj){
        return true;
    }
    if (obj == null){
        return false;
    }
    if (getClass() != obj.getClass()){
        return false;
    }
    final Person other = (Person) obj;
    if (!Objects.equals(this.licenseNumber, other.licenseNumber)){
        return false;
    }
    return true;
}

@Override
public String toString(){
    return "Person{" + "licenseNumber=" + licenseNumber + '}';
}

public boolean validateLicense(){
    boolean retValue = false;
    if ((this.licenseNumber.matches("^[a-zA-Z]{2}\\d{7}$")))
        retValue = true;
    return retValue;
}

【问题讨论】:

  • 我认为你的实施有问题
  • 例如person.equals(add)是什么意思?比较 objectboolean ?
  • person.equals(add) 如果被添加则返回 true
  • @Newb2Java 怎么样?您是否使用自己的 ArrayList 实现并覆盖了 .equals(Object obj) 方法?请edit 你的问题包括Person 类。
  • @Newb2Java 你应该看看ArrayList's documentation 尤其是remove(Object o) 部分。您的remove(String license) 方法可以像return person.remove(license); 一样简单

标签: java arrays string oop arraylist


【解决方案1】:

试试这个:

public boolean remove (String license){ //remove person with specific license from list
    Iterator<Person> personIterator = person.iterator();
    boolean remove = false;

    while(personIterator.hasNext(){
        Person personInstance = personIterator.next();  
        if(personInstance.getLicense().equals(license))){
            personIterator.remove();
            remove = true;
            break;
        }
    }

   return remove;
}

【讨论】:

  • 这段代码有语法错误。另外你怎么知道Person 类有getLicense(String license) 方法? OP 没有在他们的问题中提供 Person 类。
  • 抱歉仓促了..更新了语法..顺便说一句,检索和比较许可证的方法名称是什么..算法将起作用..即使它等于..我假设OP 足够聪明,可以推断出这一点。
  • person 的类型是 ArrayList&lt;Person&gt;,所以我们已经知道它没有方法 getLicense
  • 我忘了添加equals.. if(personInstance.getLicense().equals(license))){
  • 不确定什么是 Realtor.. 如果迭代器是在 Collection realtorCollection 上创建的;迭代器 realtorIterator = realtorCollection.iterator().. 然后是
【解决方案2】:

@Newb2Java,equals 方法可以将 person 与任何对象进行比较,但如果参数(此处为 add)与调用者(person)的类型不同,则结果是false。尽管您使用了单数名词person,但它的类型是复数,是Persons 的集合。 ArrayList&lt;Person&gt; 永远不会等于 Boolean(也不等于 boolean)。 List 方法 add 将返回 trueremove 将返回 true 如果它实际上删除了参数,它必须是 Person 类型。首先,您必须找到列表中的哪个元素具有指定的属性值。因此,您必须遍历列表,最好使用迭代器,直到找到具有给定License 的元素的每个实例。像这样的:

package practice;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class Personator {
  private final List<Person> persons = new ArrayList<>();

  public List<Person> getPersons() {
    return new ArrayList<>(persons);
  }

  public boolean add(Person person) {
    return persons.add(person);
  }

  public boolean remove(String license) {
    return remove(new Person(license));
  }

  public boolean remove(Person removal) {
    boolean wasRemoved = false;
    for (ListIterator<Person> iterator = persons.listIterator(persons.size());
       iterator.hasPrevious();
       ) {
      final Person person = iterator.previous();
      if (removal.equals(person)) {
        iterator.remove();
        wasRemoved = true;
      }
    }
    return wasRemoved;
  }
}

用这个:

public class Person {
  private final String license;

  public Person(String license) {
    if (license == null) {
      throw new IllegalArgumentException("null license not allowed");
    }
    this.license = license;
  }

  public String getLicense() {
    return license;
  }

  @Override
  public String toString() {
    return "Person " + getLicense();
  }

  @Override
  public int hashCode() {
    return getLicense().hashCode();
  }

  @Override public boolean equals(Object oth) {
    if (this == oth) {
      return true;
    }
    if (! (oth instanceof Person)) {
      return false;
    }
    Person other = (Person) oth;
    return this.getLicense().equals(other.getLicense());
  }
}

【讨论】:

    【解决方案3】:

    您的代码中有一些错误,我在下面用 cmets 突出显示了它们:

    public class PersonLogImpl {
        private boolean remove;
        private boolean isLicenseUnique;
        private boolean add;
        private final ArrayList<Person> person;
    
        public PersonLogImpl() {
            // YOU SHOULD ALSO ASSIGN THE PRIVATE BOOLEANS HERE
            this.person = new ArrayList<>();
        }
    
        public ArrayList<Person> getPersonLog() {
    
            return Person; // What's going on here?
            // You're returning the actual Person class when you should be returning
            // an ArrayList of type Person (I think you meant for the P to be lowercase)
        }
    
        public boolean add(Person obj){  //add person object to ordered list 
           person.add(obj);
    
           return add; // You never assign true or false to 'add' (I believe 
           // it defaults to true) so this method will always return true (maybe 
           // false, not sure). you should instead use 'return person.add(obj);'
        }
    
        public boolean remove (String license){ //remove person with specific license from list
    
            // The code below makes no sense (no offence).
            if(person.remove(person.equals(add))){
                    remove = true;
            }
           return remove;
    
            // Since I don't know the make up of the 'Person' class I can't 
            // tell you how this method should function. I'll make a guess though:
           for(int i = 0; i < person.size(); ++i) {
               if(person.get(i).getLicenseNumber().equals(license)) {
                   return person.remove(i);
               }
           }
    
           // OR a shorter alternative
           return person.remove(new Person(license));
        }
    
    }
    

    【讨论】:

    • 我已经添加了人员类中处理许可证号的位
    【解决方案4】:

    如果您还没有,请在您的 Person 类上创建一个方法 getLicense()。该方法应该返回 Person 的许可证,然后您可以使用下面的 remove 方法;

    编辑:我现在看到您的 Person 类上有一个 getLicenseNumber() 方法。

    public boolean remove(String license) {
       for (Person individual : person) { // go through each Person on the ArrayList
           if (individual.getLicenseNumber().equals(license)) // check if that Person's license is equal to the license we're looking for
               return person.remove(individual); // if so, remove that person and return true (remove will return true if the element is found)
       }
    
       return false; // if we never removed any element we never found a person with that license. In that case, return false
    }
    

    我假设每个人都有一个唯一的许可证号,并且您不会将同一个 Person 两次添加到 ArrayList 中(或者会阻止用户尝试添加)。 如果您希望删除任何具有该许可证的人员,您可以使用以下方法:

    public boolean remove(String license) {
        int listsize = person.size(); // size before removing any
        for(int i=0; i<person.size(); i++) {
            if (person.get(i).getLicenseNumber().equals(license))
                person.remove(i--); // i-- is required because the list size will change if we remove from it, so we need to decrement i
        }
    
        return !(listsize == person.size()); // if the size before is equal to the size now, we never removed any and thus return false
    }
    

    如果您想要更简单的解决方案,可以查看method removeAll from ArrayList class

    【讨论】:

    • 为什么 getLicense() 是必需的,因为 arraylist 将包含该值并且您可以将其删除?
    • @Harry ArrayList 包含 Person 对象而不是 String 对象。
    • ArrayList 的类型是 Person 而不是 String(如果是,我们可以return person.remove(license);。我们可以查看 ArrayList 上的每个 Person 比较许可证,或者使用该许可证创建一个新 Person并直接从 ArrayList 中删除。但由于 op 没有发布 Person 类,我不能假设哪个是最好的。
    • 你试过这个代码吗?我不确定,但我认为在迭代它时从List 中删除会引发异常(我认为是ConcurrentModificationException,但我不确定),因为 for-each 循环在后台使用迭代器。
    • 我试过了,效果很好。可能是因为一旦我们找到具有该许可证的 Person,我们将删除该 Person 并立即关闭该方法,因此它不会进入下一次迭代。
    猜你喜欢
    • 2014-05-04
    • 2016-02-14
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多