I have a class called Person
. It has the following attributes
; It has 2 attributes, ID
, and Telephone
. 1 person can have many
First of all, why are you not having a List<Integer>
for storing all your telephoneNumbers
for a particular person. That way, you won't have to create a separate Person
instance for each telephoneNumber
for the same personId
, which simply makes no sense.
You can change your attributes of Person class to: -
private int id;
private List<Integer> telephoneNumbers = new ArrayList<Integer>();
And then have a list of Person, as you are having.
To find a Person
with a particular telephoneNumber, you need to iterate through your List<Person>
.
for (Person person: personList) {
if (person.getTelephoneNumbers().contains(telephone)) {
return person;
}
}
Many solutions, define two persons as equal by their phone number but what if two persons that live in the same house and / or have the same phone number are added to the list? Which one is the correct one?.
Before rushing to find the person, you have to define a way to determine if two persons are, indeed, equal without ambiguous results. Unless you restrict the creation of persons based on that very phone number by making it unique (you do not clarify this in your question, so I assume there is no such restriction), the result of the search is undefined.
You're using an ArrayList
so you can't guarantee even a result by insertion order.
I suggest you base the equality test in a person's ID
instead of its phone. To prevent the modification of id
's just define a getter for it and do not define a setId
method at all. Then, you can redefine equals
(and hashcode
if you feel like it) based on id
.
i tried personList.contains()
Make sure you override Object.equals()
and Object.hashCode()
for Person class. But you have to have equality check on telephone number assuming telephone number unique. This would not be a solution but a workaround. Use bellum's answer. Mark it as correct answer.
Use a for
loop to iterate through the list. In the body of the loop, check if the telephone number of the person in the list is the telephone number you're looking for. If yes, then return the person.
See The for Statement in Oracle's Java Tutorials.
//...
Person foundPerson = null;
for (Person p : personList){
if (p.getTelephone() == telephone){
foundPerson = p; //or simply return it from there
break;
}
}
For implementing hashCode
and equals
you can observe this tutorial.
You need to iterate the array, check the persons one by one for phone number, and when you get to the one you need just assign it to a variable.