当前堆在java中更新

时间:2013-02-28 19:47:32

标签: java

我正在为java编写一个堆类。

类堆有

 class Heap{
     int maxsize=1000;
     int[] heap= new int[maxsize];
     int size=0;
     //.... some methods basically, print, insert and remove

     int[] sortHeap (){
         int[] sorted= new int[size];
         Heap copy= new Heap();
         copy.heap=heap;
         copy.size=size;
         int i=0;
         while (copy.size>0){
             sorted[i]=copy.remove();
             i++;
         }
         return sorted;
     }
 }

我尝试创建的一个方法是返回已排序的堆。我不想破坏原始堆。 但是,当我调用此方法时,我调用它的原始堆将被销毁。 有人可以向我解释为什么会发生这种情况吗?

例如。 说堆是 -17,
-1,-7,
1,0,2,-5,
17,57,27,3,127,9,//正确打印

现在我调用test.heapSort();然后打印结果数组。

然后在此之后打印堆得到结果

127,
127,127,
57,57,127,27,
27,57,27,3,127,9,

谢谢。

1 个答案:

答案 0 :(得分:3)

声明

copy.heap=heap;

不会复制数组。它只是将数组heap的引用分配给copy.heap。因此,两个字段:heapcopy.heap都指向同一个数组。

复制数组内容的正确方法是:

System.arraycopy(heap, 0, copy.heap, 0, heap.length);