代码之家  ›  专栏  ›  技术社区  ›  Sean Courtney

在对象内添加字符串数组[重复]

  •  -2
  • Sean Courtney  · 技术社区  · 7 年前

    我正在尝试在对象中添加字符串数组。

        public Question(int id, String question, String[] answers) {
        this.id = id;
        this.question = question;
        this.answers = answers;
    }
    

    这就是我遇到麻烦的地方

            questionList.add(
                new Question(
                        1,
                        "This is a question?",
    
        ));
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   Elliott Frisch    7 年前

    你可以用 String[] 字面语法,比如

    new String[] { "a", "b", "c" }
    

    可变参数 参数。就像,

    public Question(int id, String question, String... answers) {
        this.id = id;
        this.question = question;
        this.answers = answers;
    }
    

    字符串[] 使用逗号分隔的答案(或 (文本)来实例化它。

    new Question(
        1,
        "This is a question?",
        "This is an answer.", "This is another answer."
    )
    
        2
  •  0
  •   Steven Spungin    7 年前

    要创建“answers”参数,一种方法是。

    String[] answers = new String[]{"Answer 1", "Answer 2"};
    

    也可以将列表转换为数组。

    String[] answers = Arrays.asList("Answer 1", "Answer 2").toArray(new String[0])
    
        3
  •  0
  •   Mauricio Irace    7 年前

    new String[] {"Hellow world", "Bo mundo", "Hola Mundo" }
    

    在声明中,可以避免使用“new String[]”的内容,因为java会推断类型,但事实并非如此。因此,如果要创建新问题:

    Question question = new Question(1, "2 + 2 = ?", new String[] {"1", "2", "42"});
    

    无论如何,另一个可以用来减少这种冗长的功能是使用“…”。例如,如果您改为编写以下内容

    public Question(int id, String question, String... answers) {
        this.id = id;
        this.question = question;
        this.answers = answers;
    }
    

    Question question = new Question(1, "2 + 2 = ?", "1", "2", "42"});
    

    其中,一个又一个问题的所有参数都是answers数组的一部分。