在Java中实现点赞功能可以通过以下步骤:
public class Like {
private int userId;
private int objectId;
// 构造方法、getter和setter方法
}
import java.util.ArrayList;
import java.util.List;
public class LikeManager {
private List<Like> likes;
public LikeManager() {
likes = new ArrayList<>();
}
// 添加点赞
public void addLike(int userId, int objectId) {
Like like = new Like(userId, objectId);
likes.add(like);
}
// 取消点赞
public void removeLike(int userId, int objectId) {
for (Like like : likes) {
if (like.getUserId() == userId && like.getObjectId() == objectId) {
likes.remove(like);
break;
}
}
}
// 检查是否已点赞
public boolean hasLiked(int userId, int objectId) {
for (Like like : likes) {
if (like.getUserId() == userId && like.getObjectId() == objectId) {
return true;
}
}
return false;
}
}
public class Main {
public static void main(String[] args) {
LikeManager likeManager = new LikeManager();
// 用户1给对象1点赞
likeManager.addLike(1, 1);
// 用户2给对象1点赞
likeManager.addLike(2, 1);
// 用户1取消对对象1的点赞
likeManager.removeLike(1, 1);
// 检查用户1是否已点赞对象1
boolean hasLiked = likeManager.hasLiked(1, 1);
System.out.println(hasLiked); // 输出:false
}
}
以上是一个简单的点赞功能的实现示例,可以根据实际需求进行修改和扩展。