0

Hi i have a question about ArrayList in Java.

I have in a class called "Utente" an ArrayList ricFriends; Now, the problem is that i have a method called

requestFriendship(Utente u) 

where i want to add in the u.ricFriends the object Utente that call the method...

I tried in this way but it's at 99% wrong..

public void requestFriendship(Utente u){
    u.ricFriends.add(this);
}

for example i want to do this :

Utente Gary = new Utente();
Utente Mike = new Utente();

Gary.requestFriendship(Mike);

And if i check Mike.ricFriends i can see the object Gary;

Sorry for the english, thank you.

5
  • According your description, requestFriendship works correctly: the object for which you call this method is added to the list owned by the Utente parameter. Commented Apr 11, 2016 at 16:08
  • What exactly is your question? Commented Apr 11, 2016 at 16:08
  • That looks like it should work, what is wrong with it? Commented Apr 11, 2016 at 16:08
  • 2
    It should add Gary to Mike and seems working. Do you want to add Mike to Gary too? Commented Apr 11, 2016 at 16:09
  • Sorry, i solved, it works Commented Apr 11, 2016 at 16:15

2 Answers 2

2

Not sure what you're trying to do, but you should change this line:

 u.ricFriends.add(this);

for this:

  this.ricFriends.add(u)
Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you are making a attribute public, that's not a good practice in OO programming, you should create get and set methods.

About you problem, you could do it something like this:

ArrayList<Utente> utenteList = u.getRicFriends();

utenteList.add(Mike);

Take care about "this" pointer, "this" mean that you are taking the object reference himself.

1 Comment

Returning mutable lists is also often seen as bad practice in OO programming. I would prefer an addRicFriend(Mike) method. This would make changes in u easier - the internal detail, whether ricFriends is an Array, an ArrayList or anything else is encapsulated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.