Java Reference
In-Depth Information
Write a program that uses an
ArrayList
or
Vector
to determine which position
you should stand in to marry the princess if there are
n
suitors. Your program
should use the
ListIterator
interface to traverse the list of suitors and remove a
suitor. Be careful that your iterator references the proper object upon reversing
direction at the beginning or end of the list. The suitor at the beginning or end
of the list should only be counted once when the princess reverses the count.
7.
In “social networking” websites people link to their friends to form a social net-
work. Write a program that uses
HashMaps
to store the data for such a network.
Your program should read from a file that specifies the network connections for
different user names. The file should have the following format to specify a link:
source_usernamefriend_username
There should be an entry for each link, one per line. Here is a sample file for
five usernames:
iba
java_guru
iba
crisha
iba
ducky
crisha
java_guru
crisha
iba
ducky
java_guru
ducky
iba
java_guru
iba
java_guru
crisha
java_guru
ducky
wittless
java_guru
In this network everyone links to
java_guru
as a friend.
iba
is friends with
java_guru
,
crisha
, and
ducky
. Note that links are not bidirectional;
wittless
links with
java_guru
but
java_guru
does not link with
wittless
.
First, create a
User
class that has an instance variable to store the user's name
and another instance variable that is of type
HashSet<User>
. The
HashSet<User>
variable should contain references to the
User
objects that the current user links
to. For example, for the user
iba
there would be three entries, one for
java_guru
,
crisha
, and
ducky
. Second, create a
HashMap<String,User>
instance variable in
your
main
class that is used to map from a username to the corresponding
User
object. Your program should:
•
Upon startup read the data file and populate the
HashMap
and
HashSet
data
structures according to the links specified in the file.
•
Allow the user to enter a name.
•
If the name exists in the map then output all usernames that are one link
away from the user entered.
•
If the name exists in the map then output all usernames that are two links
away from the user entered. To accomplish this in a general way you might
consider writing a recursive subroutine.