Forums Register Login

Cannot assign cloned String array to generic type array.

+Pie Number of slices to send: Send
I have the following code in which I am looping through the rows of one array (composed of Strings) and copying it to another array. I am using .clone() to achieve this and it seems work as it changes the memory location of the rows themselves. I did notice that the String objects are still pointing to the same location in memory in both arrays but I won't worry about that for now, at the moment I just want to understand why the array I am cloning is not successfully assigning to the other array.

This is the incorrect line:

My code:



My compiler says: Required: T[]. Found: java.lang.String[]

Since ar[r] is an array and .clone() also returns an array why is this line incorrect.
+Pie Number of slices to send: Send
I don't see where you are calling the copyMaze method, but you'll notice that it has a type parameter <T>. You'll need to make sure that you use <String> for that type parameter. If you don't know how to do that (which wouldn't be that unlikely given that you posted in Beginning Java) then show us the code which is calling copyMaze.
+Pie Number of slices to send: Send
Actually the only place I wanted to use this method is in "mazeCopy" right bellow my maze declaration in the code I posted (It's the line that is commented out). I know it wouldn't make sense to have the parameter "ar" in this case since I can easily access all arrays I need, but I just wanted to test this out.
+Pie Number of slices to send: Send
Seems to me that type inference should be working in that case. But you didn't tell us which line of code had the compiler message.
+Pie Number of slices to send: Send
This line specifically:
ar[r] = maze[r].clone();

And also something to note is that if I modify the method and change all <T>, T[][], and modify the parameter types to String no errors occur.
+Pie Number of slices to send: Send
This is what I mean:


If I change the method like this I get no error.
1
+Pie Number of slices to send: Send
clone returns an Object. You can discover this by hovering over the method or pressing Ctrl-Space if you use Eclipse.

Use a cast to fix it.
crispy bacon. crispy tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 422 times.
Similar Threads
July Newsletter Puzzle (Maze Solver)
help
Maze Solving
Custom Clone and garbage collection
Storing a text file into a 3d Array
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:49:10.