Java社交媒体用户系统设计:用户和好友类实现
以下是使用Java语言设计的社交媒体用户系统的示例代码:
import java.util.ArrayList;
import java.util.List;
class User {
private int userId;
private String username;
private String profile;
private List<Friend> friends;
public User(int userId, String username, String profile) {
this.userId = userId;
this.username = username;
this.profile = profile;
this.friends = new ArrayList<>();
}
public int getUserId() {
return userId;
}
public String getUsername() {
return username;
}
public String getProfile() {
return profile;
}
public void addFriend(Friend friend) {
friends.add(friend);
}
public List<Friend> getCommonFriends(User otherUser) {
List<Friend> commonFriends = new ArrayList<>();
for (Friend friend : friends) {
if (otherUser.hasFriend(friend)) {
commonFriends.add(friend);
}
}
return commonFriends;
}
private boolean hasFriend(Friend friend) {
for (Friend userFriend : friends) {
if (userFriend.getFriendId() == friend.getFriendId()) {
return true;
}
}
return false;
}
}
class Friend {
private int friendId;
public Friend(int friendId) {
this.friendId = friendId;
}
public int getFriendId() {
return friendId;
}
}
public class SocialMediaUserSystem {
public static void main(String[] args) {
// 创建用户对象
User user1 = new User(1, 'User1', 'Profile 1');
User user2 = new User(2, 'User2', 'Profile 2');
User user3 = new User(3, 'User3', 'Profile 3');
// 创建好友对象
Friend friend1 = new Friend(2);
Friend friend2 = new Friend(3);
// 添加好友关系
user1.addFriend(friend1);
user2.addFriend(friend1);
user2.addFriend(friend2);
user3.addFriend(friend2);
// 查找共同好友
List<Friend> commonFriends = user1.getCommonFriends(user2);
System.out.println('共同好友:');
for (Friend friend : commonFriends) {
System.out.println(friend.getFriendId());
}
}
}
该社交媒体用户系统包含两个类:User和Friend。User类表示用户,包含用户ID、用户名和个人资料等属性。Friend类表示好友,包含好友ID等属性。
在User类中,使用List集合来存储用户的好友关系。addFriend方法用于添加好友关系,getCommonFriends方法用于查找与另一个用户的共同好友。
在SocialMediaUserSystem类的main方法中,先创建几个用户对象和好友对象。然后通过调用addFriend方法将好友关系添加到对应的用户中。最后,调用getCommonFriends方法查找用户1和用户2的共同好友,并打印出来。
原文地址: https://www.cveoy.top/t/topic/bDgU 著作权归作者所有。请勿转载和采集!