0

So I'd like to copy a variable in Java without them sharing the same dataset. The variable is an array called ChunkSection[] tsec and I'd like to copy it to ChunkSection[] sec but without the two having any sort of relationship. I've tried .clone() but it didn't work.

ChunkSection[] sec = null;
tsec = fromChunk.i().clone();
for (ChunkSection s : tsec) {
    ArrayList<ChunkSection> chs = new ArrayList<>();
    chs.add(s);
    sec = (ChunkSection[]) chs.toArray();               <-----
}

The code above generates a ClassCastException on the line that arrow points to.

Tim
  • 41,901
  • 18
  • 127
  • 145
ThePixelPony
  • 721
  • 2
  • 8
  • 30
  • 1
    Use the overloaded `toArray(T[] arr)` method. – Alexis C. May 08 '14 at 17:03
  • possible duplicate of [java: (String\[\])List.toArray() gives ClassCastException](http://stackoverflow.com/questions/5690351/java-stringlist-toarray-gives-classcastexception) – Alexis C. May 08 '14 at 17:04

1 Answers1

1

Use Arrays.copyOf to make a copy of an array.

ChunkSection [] sec = Arrays.copyOf(tsec, tsec.length);
David Stanley
  • 333
  • 3
  • 12