在Java中實(shí)現(xiàn)點(diǎn)贊功能可以通過(guò)以下步驟:
public class Like {
private int userId;
private int objectId;
// 構(gòu)造方法、getter和setter方法
}
import java.util.ArrayList;
import java.util.List;
public class LikeManager {
private List<Like> likes;
public LikeManager() {
likes = new ArrayList<>();
}
// 添加點(diǎn)贊
public void addLike(int userId, int objectId) {
Like like = new Like(userId, objectId);
likes.add(like);
}
// 取消點(diǎn)贊
public void removeLike(int userId, int objectId) {
for (Like like : likes) {
if (like.getUserId() == userId && like.getObjectId() == objectId) {
likes.remove(like);
break;
}
}
}
// 檢查是否已點(diǎn)贊
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給對(duì)象1點(diǎn)贊
likeManager.addLike(1, 1);
// 用戶2給對(duì)象1點(diǎn)贊
likeManager.addLike(2, 1);
// 用戶1取消對(duì)對(duì)象1的點(diǎn)贊
likeManager.removeLike(1, 1);
// 檢查用戶1是否已點(diǎn)贊對(duì)象1
boolean hasLiked = likeManager.hasLiked(1, 1);
System.out.println(hasLiked); // 輸出:false
}
}
以上是一個(gè)簡(jiǎn)單的點(diǎn)贊功能的實(shí)現(xiàn)示例,可以根據(jù)實(shí)際需求進(jìn)行修改和擴(kuò)展。