gpt4 book ai didi

java - 添加到 ArrayList 时出现问题

转载 作者:行者123 更新时间:2023-12-01 17:50:53 25 4
gpt4 key购买 nike

我看过视频、搜索过这个网站和许多其他网站,但没有什么真正有帮助的。这是我第一次使用ArrayList。如果我将 ArrayList 作为字符串,那很好,但是一旦我设置 Comment(这是类),它就不再起作用。但导师暗示这就是它的用途。我还有另外两个类需要访问它,显然还有 main 方法。

我遇到的主要问题是它不允许我添加到数组列表中。我很困惑,这可能真的很简单。

public class Comment {

// somehow need to link it to the game/app
private ArrayList<Comment> Reply = new ArrayList<Comment>();

private String usrComment;
private String usrID;

public Comment() {
}

public Comment(String usrID, String usrComs) {
this.usrComment = usrComs;
this.usrID = usrID;
}

public void addReview(String addRev) {

this.Reply.add(addRev); // not working
}

public void addReply(String addRep) {

Reply.add(addRep); // not working and I cannot figure it out
}

public void printRep() {
for (Comment comment : Reply) {
System.out.println(comment);
}
}

}

最佳答案

问题是您正在尝试添加一个String,但数组列表需要一个Comment

public void addReview(String addRev) {
// Reply is an ArrayList<Comment> of Comments not of Strings
// this.Reply.add(addRev); // not working
// you can create a new Comment and then add that comment
this.Reply.add(new Comment("userId", addRev));
}

public void addReply(String addRep) {
// same here
// Reply.add(addRep); // not working and I cannot figure it out
// you can create a new Comment and then add that comment
this.Reply.add(new Comment("userId", addRep));
}

关于java - 添加到 ArrayList 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50306933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com