NullPointerException的问题

时间:2014-09-17 12:22:59

标签: 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 个答案:

答案 0 :(得分: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);
}

你应该总是制作私人,可变数据的防御性副本。