Last active
August 1, 2017 07:37
-
-
Save omayib/64fcfe68bb3794a4da6d0464dc69b967 to your computer and use it in GitHub Desktop.
how to identify an object by specific attribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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