Question
using given code to finish In the previous lab you created a Person class. Now, in this activity change the design of the Person class,
using given code to finish
In the previous lab you created a Person class. Now, in this activity change the design of the Person class, in which the list of friends of a person will be stored in an ArrayList, instead of a String. Then, provide getter and setter methods to get the name of a friend using a given position or set the name of an existing friend, respectively. In your tester class, test your class and also printout the list of all friends of a given person object.
package javalab4;
public class Person { private String name; private String friendList;
// Construcor to create object of Person with the given name and // initialize friendlist with empty string public Person(String name) { this.name = name; friendList = new String(""); }
// Add person to the friend list public void befriend( Person p ) { // Concatenate the name of person to the list followed by space this.friendList = this.friendList + p.getName() + " "; }
// Function to unfriend a Person from the list of friends public void unfriend ( Person p ) { // Create a regular expression for the given name of the person String rgx = "\\s*\\b" + p.getName() + "\\b\\s*"; // Replace all the occurences of that name with space friendList = friendList.replaceAll(rgx, " "); }
// Return the name of the Person public String getName( ) { return this.name; }
// Returns list of friends of the Person public String getFriendNames( ) { return friendList; }
public static void main(String[] args) { // Create objects with different names Person pr = new Person("Akos"); Person pr1 = new Person("Tim"); Person pr2 = new Person("Sam"); Person pr3 = new Person("Leo");
pr.befriend(pr1); pr.befriend(pr3); pr.befriend(pr2);
System.out.println("Friend list of " + pr.getName() + ": " + pr.getFriendNames()); pr.unfriend(pr3); System.out.println("Friend list of " + pr.getName() + " after unfriending Leo: " + pr.getFriendNames()); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started