Part (a)
/** @param people a set of Person objects
* @return a set containing all members of people and all the
* immediate contacts of all members of people
* Postcondition: the set people is unchanged
*/
private static Set<Person> expandContactSet(Set<Person> people)
{
Set<Person> c = new TreeSet<Person>(); 1
for (Person p : people)
{
c.add(p);
for (Person p1 : p.getContacts())
c.add(p1);
}
return c;
}
Notes:
Strictly speaking, for using a TreeSet<Person> , Person
must implement Comparable<Person> .
Using a TreeSet assures that the names of Person s appear in
alphabetical order when the set is printed out.
It is also possible to use a HashSet :
Set<Person> c = new HashSet<Person>();
Then Person must have a hashCode method
and an equals method;
we can assume they are provided but "not shown."
Part (b)
/** Creates and returns a set containing all members of this person's network of contacts
* who are within distance dist away
* @param dist the maximum distance between this person and a network contact
* Precondition: dist > 0
* @return a set of contacts who are within distance dist away from this person
* Postcondition: this person is not included in the returned set
*/
public Set<Person> getNetwork(int dist)
{
Set<Person> people = getContacts();
for (int d = 2; d <= dist; d++)
people = expandContactSet(people);
people.remove(this);
return people;
}
|