1
I wonder if it is possible to iterate a list that is in another class.
On a social network, every user has a list of posts, but this list is defined only in the class User
how to iterate inside it ?
Method I want to apply:
rede.addComment ("u3", "u1", "p1", new Comment ("c1",
"Com pão de queijo ? tudo di bão"));
Class SocialNetwork
:
import java.util.ArrayList;
import java.util.List;
public class SocialNetwork {
private List<User> users;
public SocialNetwork () {
users = new ArrayList<User>();
}
public void addUser(User user) {
users.add(user);
}
public User getUserById(String id) {
for (User u : users) {
if (id == u.getId())
return u;
}
return null;
}
private Post getPostById(Post post, User id) {
for (User getUserById(id) i : posts) {
}
return null;
}
public void addPost(String id, Post post) {
User userId = getUserById(id);
userId.addPost(post);
}
public void addComment(String user1, String user2, String postId, Comment comment) {
User userComented = getUserById(user1);
User userPosted = getUserById(user2);
Post post = getPostById(postId);
}}
Class User
:
import java.util.ArrayList;
import java.util.List;
public class User {
private String id;
private String name;
private List<User> friends;
private List<Post> posts;
public User(String id, String name) {
this.id = id;
this.name = name;
friends = new ArrayList<>();
posts = new ArrayList<>();
}
public void addFriend (User friend) {
friends.add(friend);
}
public void addPost (Post post) {
posts.add(post);
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public List<Post> getUserPosts() {
return this.posts;
}
@Override
public String toString() {
return "(" + id +"," + name +")";
}}
Class Post
:
import java.util.ArrayList;
import java.util.List;
public class Post {
private String id;
private String content;
private List<Comment> comments;
private List<String> likes;
public Post(String id, String content) {
this.id = id;
this.content = content;
comments = new ArrayList<>();
likes = new ArrayList<>();
}
public String getId() {
return id;
}
public String getContent() {
return content;
}
public void addComment (Comment comment) {
comments.add(comment);
}}