gpt4 book ai didi

java - NullPointerException 的问题

转载 作者:行者123 更新时间:2023-12-01 12:31:36 26 4
gpt4 key购买 nike

今天我遇到了这个评估问题,我必须创建两个类:Dress 和 TestClass。我完成了这些类(class),但是当我尝试运行该程序时,我收到了 NullPointerException 消息。这是我的类(class):

类(class)着装:

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

最佳答案

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

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.

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

这是正确的方法(为了清楚起见,仅采用一种方法):

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

您应该始终为私有(private)、可变数据制作防御性副本。

关于java - NullPointerException 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com