在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
}
}
以上是一個簡單的點贊功能的實現示例,可以根據實際需求進行修改和擴展。