Ragnar Ragnar - 25 days ago 7
Java Question

How to use a boolean in an "else if" directed to objects from an ArrayList

Ok hello there. To begin with, excuse me if my English looks poor at any point; not really my mother tongue. Also, excuse me for any horrible coding mistakes but i am a beginner in Java/coding.

So let me explain what's the problem and hopefully you can help me:

There is a simplified Social Network that has Users and Groups. Users can also become friends.

There are regular groups and closed groups (sub-class of Groups). The difference is that in closed groups, you can only join if: 1) you are the first member of the group to join or 2) if you have a friend in the group already (in this case obviously someone has already joined the group before you so condition #1 fails).

Here's the thing. Essentially, every user has an ArrayList to store his friends (named "friendList"). There is also an ArrayList in class "Group" to store the users that are enrolled in the group (named "members").

When it comes to ClosedGroups, i have an "if" to check if the ArrayList of the group is empty. If it is, then i add the user. From then on, i need to check if the user that wants to join exists in the friendlist of an already existing member, and this is where i don't really know what to do. The "addMember" method of class "ClosedGroup" goes as stated below.

public void addMember(User aUser){
if(members.isEmpty()){
members.add(aUser);
aUser.addGroup(this);
System.out.println(aUser.getName() + " has successfully been enrolled in group " + this.getName());
}
else if(){
members.add(aUser);
aUser.addGroup(this);
System.out.println(aUser.getName() + " has successfully been enrolled in group " + this.getName());
}
else{
System.out.println("FAILED: " + aUser.getName() + " cannot be enrolled in group " + this.getName());
}


So, what exactly do i have to type in this "else if" ?

Additionally, it is asked to have a method in class "User" that will return true (if 2 users are friends) or false, which i am also probably doing wrong.

Help, kind devs.

Thanks in advance.

EDIT: Disjoint worked like a charm. Thank you very much for the suggestion guys!

Joe Joe
Answer

Check out the disjoint method of the Collections class: http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#disjoint%28java.util.Collection,%20java.util.Collection%29

This will return true if there are no elements the same.

if(!Collections.disjoint(members, aUser.getFriends()))