有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是NullPointerException的一个问题

今天我有一个评估问题,我必须创建两个类:Dress和TestClass。 我完成了这些类,但当我试图运行该程序时,收到一条NullPointerException消息。以下是我的课程:

班级服装:

public class Dress {
    String colors []; 
    int sizes [];

    public Dress ( String colors [], int sizes []){
       this.colors = new String [colors.length];
       this.sizes = new int [sizes.length] ;
       this.colors = colors;
       this.sizes = sizes;
    }

    public boolean search (String color){
       for (int i =0; i<colors.length;i++)
           if (colors [i].equals(color))
              return true;
       return false;
    }
    public boolean search (int size){
       for (int i =0; i<sizes.length;i++)
           if (sizes [i] == size)
              return true;
       return false;
    }
}

类测试:

public class Tests {
    public static void main (String args []){
       String color[] = {"Pink","Blue","Red"};
       int size[] = {8,9,7};
       Dress d = new Dress (color, size);
       System.out.println(d.search("Pink"));
       System.out.println(d.search(8));
    }
}

共 (1) 个答案

  1. # 1 楼答案

    仅供参考-将可变引用分配给私有数据成员不是一个好主意:

    this.colors = new String [colors.length];  // The new reference is discarded after reassignment on next line
    this.colors = colors;  // The program that passes this reference can modify it; changes will be visible to your class instance.
    

    任何获得该引用并更改其状态的人都将更改您的实例数据成员,而不考虑其私有状态

    以下是正确的方法(为了清晰起见,只有一种):

    public Dress(String [] colors) {
        if (colors == null) throw new IllegalArgumentException("colors cannot be null");
        this.colors = new String[colors.length];
        // Copy the values from the parameter array into the new, private array.
        System.arraycopy(colors, 0, this.colors, 0, this.colors.length);
    }
    

    您应该始终制作私有、可变数据的防御性拷贝