Java - refering to an object

I'm new in Java and I'm trying to create a social network. I have a array of objects "People" which their names, e-mails and so on. I would like to create relations between them (like 'friends') so that program would connect two object.

I though about doing another array inside of every "Person" object, so each person would have a name, e-mail and friend array with all friends inside of it. I don't know how to refer to an other object of type People inside of object of this type.

I don't know if it's clear.. Hope it is! Thank You in advance!

Answers


Here's one way:

public class Person {
    private String name;
    private String email;
    private List<Person> friends;

    // Leave the rest for you.

    public void addFriend(Person p) { 
        if (p != null) {
            this.friends.add(p);
        }
    }

    public void removeFriend(Person p) {
        this.friends.remove(p);
    }

    public boolean isFriend(Person p) { 
        return this.friends.contains(p);
    }
}

You'll want constructors and a way to add and remove Person from your friend List.


Need Your Help

Use many to many relationship for all models

php mysql frameworks laravel polymorphism

What are the disadvantages of implementing many to many relationships for all models? I think it would be easy to manage if something that requires it happened in the future.

Code coverage for Mocha in Windows 7

windows node.js mocha istanbul

I am trying to do code coverage for mocha using istanbul which I have installed globally: