繁体   English   中英

问题添加到ArrayLists

[英]Issues adding to ArrayLists

我看过视频,搜索过该网站以及许多其他网站,但没有任何帮助。 这是我第一次使用ArrayLists。 如果我将ArrayList作为String可以,但是一旦我设置Comment(这是该类),它就不再起作用。 但是导师暗示这就是它的用法。 我还有另外两个需要访问它的类,当然还有main方法。

我遇到的主要问题是它不允许我添加到arraylist。 而且我很困惑,这可能真的很简单。

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));
}

您可以修改代码以执行以下操作:

/**
 *id - ID of the user reviewing the comment
 *review - The review comment made by the user
 */
public void addReview(String id, String review) {
this.Reply.add(new Comment(id,review));
}

/**
 *id - ID of the user replying
 *review - The reply comment made by the user
 */
public void addReply(String id, String reply) {
this.Reply.add(new Comment(id,reply));
}

要打印注释,可以添加toString方法,如下所示:

public String toString(){
  return "ID : "+this.usrID+", Comment : "+this.usrComment;
}

这样,System.out.println(comment); 将打印:

ID : 123412, Comment : This is a comment

对于这样实例化的对象:

Comment comment = new Comment("123412", "This is a comment")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM