微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将字符串值与arraylist <object>进行比较

如何解决将字符串值与arraylist <object>进行比较

我有一类人。

Public class Person{

private String name = "";

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}

现在我有一个类,并且在该类中我声明了一个arraylist

public class AddPerson {
public ArrayList<Person> pers = new ArrayList<Person>();

//here we add some persons to the arraylist
pers.add(new Person("Simon"));
pers.add(new Person("Oscar"));
pers.add(new Person("Alfred"));

String name = "Simon";
pers.contains(name); //return false
pers.equals(name); //return false 

//I also want to be able to return the value and index of the name in arraylist if it exsists.
if(pers.contains(name)) //return index and value
}

当我尝试检查两个字符串是否相等或列表中已经有一个字符串时,我都得到了假。我做了一些研究,发现我需要重写equals方法(以及mabey hash和contains方法)。我不知道该怎么做,也找不到很好的参考资料。请帮助我实现这一目标。

解决方法

那是因为您要比较字符串("simon")和从字符串(Person("Simon")构建的对象Person。这是两个不同的对象,因此通常以false作为结果。

您是否要比较两个Person(这很有意义),或者您实际上是在尝试比较一个字符串和一个人,这无疑是一个坏主意(您实际上不能比较苹果和桔子) ,这里也一样)。

您可能想做的是

  1. 覆盖Person的{​​{1}}方法,例如,如果它们具有相同的equals,则返回true。 =>比较name s
  2. 迭代Person数组并通过pers获取其name属性,以与您进行比较getName() string =>比较name s

1 =>

String

2 =>

@Override
public boolean equals(final Object o) {
    if (this == o) {
        return true;
    }
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    final Person person = (Person)o;
    return name.equals(person.name);
}

@Override
public int hashCode() {
    return Objects.hash(name);
}
,

这里的问题是您正在使用contains方法将Person对象与String对象进行比较,因此实际上在这种情况下没有必要实现equals()方法和hashCode()方法或使用contains()方法来解决只需检查此人的属性名称是否与您比较的名为name的字符串相等。

示例解决方案:

String name="Simon";

Person result  = null;//To store the person object if a person name Simon found in the list
int personIndex = -1; //To store the index of founded person
int indexCount =-1;//To maintain the current index value of arrayList

for(Person tempPerson:pers){//Iterating the list to find a person name Simon
   indexCount++;
   if(pers.getName().equals(name)){
         personIndex = indexCount;
         result = tempPerson;
    }
}

现在,您可以将personIndex和indexCount变量中的值用于将来的计算。您可以使用if(personIndex >= 0)之类的条件来检查在迭代之后是否真的找到了具有比较名称的人,然后可以获得结果可变值。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。