Forums Register Login

Arrays.copyOf java.lang.NullPointerException

+Pie Number of slices to send: Send
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)
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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?


1
+Pie Number of slices to send: Send
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.
Can you hear that? That's my theme music. I don't know where it comes from. Check under this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 2964 times.
Similar Threads
Query about compareTo() method
How to set default values in an spring form input?
Setting up JavaBeans and Java Classes
compilation error when comping entity bean
Error setting the expression with value [Ljava.lang.String;@1d05b0a
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 03:32:08.