简体   繁体   中英

Java Arraylist of classes (custom data types), how to use contains

in a simple ArrayList, I can use contains like this :

ArrayList<String> names = new ArrayList<String>();
names.add("John");
names.add("Peter");
String find = "Peter";
if (names.contains(find)) 
System.out.println("I FOUND IT");

but how do I use contains (or something similar), if I have an ArraList of classes (custom data type)?

public class Person {
   public String name;
   public int age;

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

public String getName() {
    return this.name;
}
public String getAge() {
    return this.age;
}
}
ArrayList<Person> somePerson = new ArrayList<Person>();
somePerson.add(new Person("John","25"));
somePerson.add(new Person("Peter","84"));

How do I find in this ArrayList just the name "Peter", or just the score of "84"? I'm using loops and

if (somePerson.get(i).getName().contains(find))

but is there a way without loops, like in the simple ArrayList above?

To quote https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html :

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object o) method says: "returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e))."
[...] Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two elements. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.)

In other words, your custom classes need to implement the equals() and hashCode() methods according to the contract of those methods, which states that equal objects should have equal hash codes. (But equal hash codes do not necessarily mean that the objects are equal, though it should be avoided to have implementations that easily result in such collisions.)

You have to overide the equals method in the Person class as follows:

public class Person {
   public String name;
   public int age;

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

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

   }

   public Person(int age) {
       this.age = age;

   }

   public String getName() {
    return this.name;
   }

   public int getAge() {
    return this.age;
   }

   @Override
   public boolean equals(Object other) {
      if (!(other instanceof Person)) {
        return false;
      }

      Person p = (Person) other;
      try {
         return this.name.equals(p.name) || this.age == p.age;
      } catch (Exception e) {
        return this.age == p.age;
      }

   }

    @Override
    public String toString() {
       return name + " " + age;
    }
}

Here is the main code

import java.util.ArrayList;
import org.apache.commons.lang3.ArrayUtils;

public class MainDemo {

public static void main(String[] args) {
    ArrayList<Person> somePerson = new ArrayList<Person>();
    Person person1 = new Person("John", 25);
    Person person2 = new Person("Peter", 84);

    somePerson.add(person1);
    somePerson.add(person2);


    System.out.println("Is John there?: "+ somePerson.contains(new Person("John")));  // true
    System.out.println("Is Paul there?: "+ somePerson.contains(new Person("Paul")));  // false
    System.out.println("Is age 84 (Peter) there?: "+ somePerson.contains(new Person(84))); //true
    System.out.println("Is there a person with age 9 ?: "+ somePerson.contains(new Person(9))); //false


    searchPersonByName(somePerson, "Peter");
    searchPersonByName(somePerson, "John");
    searchPersonByName(somePerson, "Paul"); // not found

    searchPersonByAge(somePerson, 25); // will print  John 25
    searchPersonByAge(somePerson, 84); //will print Peter 84
    searchPersonByAge(somePerson, 102); // not found


}

public  static void searchPersonByName(ArrayList<Person> personsList, String name){

    Person[] personArray = personsList.toArray(new Person[personsList.size()]); // converting arrayList to Array

    String str = personsList.contains(new Person(name))?personsList.get(ArrayUtils.indexOf(personArray, new Person(name))).toString():"Not found";
    System.out.println(str);
}

public static void searchPersonByAge(ArrayList<Person> personsList, int age){
    Person[] personArray = personsList.toArray(new Person[personsList.size()]);

    String str = personsList.contains(new Person(age))?personsList.get(ArrayUtils.indexOf(personArray, new Person(age))).toString():"Not found";
    System.out.println(str);

}


}

Here you have the output:

Is John there?: true
Is Paul there?: false
Is age 84 (Peter) there?: true
Is there a person with age 9 ?: false
Peter 84
John 25
Not found
John 25
Peter 84
Not found

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