Aloysius Aloysius - 3 months ago 18
Java Question

Arraylist not adding java

I am doing a simple sch program to add friends, which is to add objects into an arraylist. I followed everything but my method befriend() doesn't seem to work.
When i manually test using the .add() in the main, it works. Where am i doing wrongly?

import java.util.*;
public class NetworkFriends {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here



Person me = new Person("Aloysius", 1);

ArrayList<Person> myList = new ArrayList<Person>(Arrays.asList(me.getFriendList()));

Person p1 = new Person("Gorgon", 2);
Person p2 = new Person("Eddy", 3);

me.befriend(p1);

for(Person i : myList) {
System.out.println("Name: " + i.getName());
}
}
}

class Person
{
private int id;
private String name;
private ArrayList<Person> friendList;
private static int runningNum = 0;
private static int friendsLimit = 5;
private String degree;
private int degreeNum;

/* Constructor - 1 param */
public Person(String name, int degreeNum)
{
//Implement your code here..
//Initialize all necessary variable(s)
this.name = name;
friendList = new ArrayList<Person>(5);
this.degree = degree;
this.degreeNum = degreeNum;
}

public void befriend(Person p){
//Implement your code here..

ArrayList<Person> anotherList = new ArrayList<Person>(Arrays.asList(p.getFriendList()));

for(Person i : friendList) {
if(!isFriend(this) && friendList.size() < 5) {
friendList.add(p);
anotherList.add(this);
}
else if(!isFriend(this) && friendList.size() == 5) {
System.out.println("Friends limit reached");
}

else {
System.out.println("Already in friend list");
}
}

}
}

public boolean isFriend(Person p){
//Implement your code here..

boolean isItAFriend = true;
for(Person i : friendList) {
if(friendList.contains(p)) {
isItAFriend = true;
}
else {
isItAFriend = false;
}
}
return isItAFriend;

}

Answer

The problem is with the foreach loop in your befriend method. You are creating a new Person with the constructor that creates a empty friend list with an initial size of 5, but is still empty.

In your befriend method, you then are looping for each friend in this empty list. So the code within the loop will not be executed and the friend is never added to a list.

I suspect you want to do something like this: (and as this looks like homework I will only give you pseudo-code)

  1. Is the person already a friend
    • Yes - nothing needs to be done or give feedback and return
    • No - Continue
  2. Have they reached their friend limit
    • Yes - display feedback and return
    • No - Continue
  3. Add the friend