索引变量String参数时出现NullPointerException

awe*_*ezy 1 java string variables parameters nullpointerexception

我是使用省略号的想法的新手.我几乎可以肯定我的错误是由于不正确地声明或初始化" String[] authors" 引起的,但我不知道如何做到这一点仍然让我的setAuthors方法工作.

import java.util.*;
public class Book {
    private String[] authors; //I'm guessing this line should end with "= new String..."
                              //but not sure how to w/o specifying an array dimension
    private int authorsSize;

    //Receives variable # of String parameters and indices them into String[] "authors"
    public void setAuthors(String... authors) {
        authorsSize = authors.length;
        for(int i=0;i<authorsSize;i++)
            this.authors[i] = authors[i];
    }
Run Code Online (Sandbox Code Playgroud)

// getAuthors方法:

    public String getAuthors(){
         String s = "";
         authorsSize = authors.length;
              for(int i=0;i<authorsSize;i++)
              s = s+authors[i] + ", ";
         printAuthors = s;
         return s;
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

最简单的办法也只是克隆数组:

public void setAuthors(String... authors){
    this.authors = (String[]) authors.clone();
}
Run Code Online (Sandbox Code Playgroud)

毕竟,你无论如何都要覆盖以前的数据,并且在方法调用之前你无法知道大小.此时您不需要authorsSize变量 - 您已经拥有authors了解自己长度的数组.

(如果你能够使用不可变集合,当然你甚至不需要打扰克隆.)

编辑:如注释中所述,如果传入空引用,此方法将引发异常.您不应该自动决定这是您应该"处理"的情况 - 记录参数不能为空是完全合法的.我建议以任何方式记录无效的行为.

实际上,如果你这样做,你可能想要初始化你的实例字段,如下所示:

private String[] authors = new String[0];
Run Code Online (Sandbox Code Playgroud)

这样你总是知道你在该字段中有一个非空引用,所以你可以使用它而不受惩罚.我更喜欢这个,因为必须在每次使用时检查null.