• Post Reply Bookmark Topic Watch Topic
  • New Topic

Arrays.copyOf java.lang.NullPointerException  RSS feed

 
albert kao
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am learning about Arrays.copyOf.
Please help to fix the following java.lang.NullPointerException.
Thanks.





Run time output:
user firstName0 i 1
user firstName1 i 2
user2s length 2
Exception in thread "main" java.lang.NullPointerException
at ArrayDemo.main(ArrayDemo.java:24)
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because assignment won't work in enchanced for loop.

An example:


The array is filled with nulls before and after the loop. You did the same in you code hence NullPointerException later.
 
albert kao
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I modify the code to the following.


The runtime output is as follows.
Please help.
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:2763)
at ArrayDemo.main(ArrayDemo.java:19)
user firstName0 i 0
user firstName1 i 1
user2 length 2
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is line:You try to copy array into wrong type!

From Arrays.copyOf javadoc:
Throws:
ArrayStoreException - if an element copied from original is not of a runtime type that can be stored in an array of class newType


In your program User2 is not a User.
The big mistake you are making id to have separate classes with different names that do exactly the same thing! Ant they are not interchangeable.
My suggestion is: delete User2 class entirely.
 
albert kao
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java doc for "Arrays" has the following:
[javadoc]public static <T,U> T[] copyOf(U[] original,
int newLength,
Class<? extends T[]> newType)[/javadoc]

What is the relationship between the "T" and "U" class?


 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Technically... none. You can put anyfing in place of U and T.
But if an element from U[] can't go into T[] you'll get an ArrayStoreException exception.
For example if U is String and T is Integer. It is because String is not Integer.
Or for example id U is User and T is User2. Because User is not User2.


Ideally U should be supertype of T.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!