Skip to content

Instantly share code, notes, and snippets.

@omayib
Last active August 1, 2017 07:37
Show Gist options
  • Save omayib/64fcfe68bb3794a4da6d0464dc69b967 to your computer and use it in GitHub Desktop.
Save omayib/64fcfe68bb3794a4da6d0464dc69b967 to your computer and use it in GitHub Desktop.
how to identify an object by specific attribute
/**
* Created by omayib on 01/08/17.
*/
public class YourApps {
public static void main(String[] args) {
Person arif = new Person("Arif", 20, 163);
Person akbarul = new Person("Akbarul", 25, 160);
Person huda = new Person("Huda", 21, 165);
//insert the data into customers list.
List<Person> customers = new ArrayList<Person>();
customers.add(arif);
customers.add(akbarul);
customers.add(huda);
//i want to search the person who has 25 years old and height 160 cm.
Person whoIam = new Person("?", 25,160);
// lets check that list of customers contain person you looking for
System.out.println(customers.contains(whoIam));
// where is index position the person you are looking for?
System.out.println(customers.indexOf(whoIam));
// who i am?
int indexOfWhoIam = customers.indexOf(whoIam);
System.out.println(customers.get(indexOfWhoIam).name);
}
static class Person{
final String name;
final int age;
final int height;
Person(String name, int age, int height) {
this.name = name;
this.age = age;
this.height = height;
}
/*
* The equals and hashcode can be generated by right click your java editor or
* If you are using Intellij Idea, you can press alt+insert
* then choose `equals()` and `hashcode()`.
* please check the attribute which will be a unique identifier.
* in this case i check `age` and `height`.
* */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (age != person.age) return false;
return height == person.height;
}
@Override
public int hashCode() {
int result = age;
result = 31 * result + height;
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment