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.
-
According your description, requestFriendship works correctly: the object for which you call this method is added to the list owned by the Utente parameter.laune– laune2016年04月11日 16:08:31 +00:00Commented Apr 11, 2016 at 16:08
-
What exactly is your question?slartidan– slartidan2016年04月11日 16:08:43 +00:00Commented Apr 11, 2016 at 16:08
-
That looks like it should work, what is wrong with it?Andrew Aitken– Andrew Aitken2016年04月11日 16:08:53 +00:00Commented Apr 11, 2016 at 16:08
-
2It should add Gary to Mike and seems working. Do you want to add Mike to Gary too?kamaci– kamaci2016年04月11日 16:09:42 +00:00Commented Apr 11, 2016 at 16:09
-
Sorry, i solved, it worksEdoardo Maurizio– Edoardo Maurizio2016年04月11日 16:15:40 +00:00Commented Apr 11, 2016 at 16:15
2 Answers 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)
Comments
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
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.