1

I am currently learning Java and am trying to work through learning generics. I have the class Holder which takes varargs. I am trying to place these into an array myArray for future use. However I get a NullPointerException on the arraycopy line and I can't seem to figure out why.

class Holder<T> {

  T[] myArray;

  public Holder(T... args) {
    System.arraycopy(args, 0, myArray, 0, args.length);  //null pointer exception
  }

This is what I am using to create the instance:

Holder<Integer> mySample = new Holder<>(1,2,3);
4
  • 5
    myArray is not initialised (it is null) Commented Apr 30, 2013 at 6:06
  • Add a breakpoint at this line and see which of (args or myArray is null). Commented Apr 30, 2013 at 6:08
  • 1
    Pro tip: You can clone arrays, so you could ditch that complicated arraycopy call and just say myArray = args.clone(); Commented Apr 30, 2013 at 6:12
  • myArray = args.clone() fixed it. Just curious how would I initialise myArray without getting a "generic array creation" error? Commented Apr 30, 2013 at 6:19

2 Answers 2

3

it is because myarray is not initialized.

T[] myArray; // `myarray` is uninitialized, as of now.

public Holder(T... args) {
    if(args != null && args.length > 0) {
        myArray = new t[args.length]; // `myarray` is initialized here.
        System.arraycopy(args, 0, myArray, 0, args.length);
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Make a null and 0 length check of args and you have yourself a nice answer ;)
@MadProgrammer 0 length array shouldn't cause any problem
No, but why waste a call to arrayCopy :P
@MadProgrammer why null check? This code should break if you pass it null instead of a proper array. If you let myArray be null you're just deferring the problem to a later occasion, which makes it harder to find the error.
Generally, checking for null is good practice. NullPointerException is an unchecked exception, meaning it won't be caught by normal try-catch blocks. Better to simply allow the myArray to remain null (which matches the requirements of the method) then crash the program - IMHO. Programming by exception is never a good idea ;)
|
0
 System.arraycopy(args, 0, myArray, 0, args.length); 

1)myArray is not intialized .

2)and possibility of args to be null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.