Reputation: 3
Today I had this evaluation question where I had to create two classes: Dress and TestClass. I finished up those classes but when I tried to run the program I got a NullPointerException message. Here are my classes:
Class Dress:
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;
}
}
Class Tests:
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));
}
}
Upvotes: 0
Views: 98
Reputation: 308733
FYI - it's a bad idea to assign a mutable reference to a private data member:
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.
Anyone who gets ahold of that reference and changes its state will be altering your instance data member as well without regard for its private status.
Here's the right way to do it (just one for clarity):
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);
}
You should always make defensive copies of private, mutable data.
Upvotes: 1