2013-04-18 50 views
1

我在使用arraycopy从阵列中删除项目时遇到问题。 我有两种方法找到(找到要删除的项目的索引)和 删除(删除)。 它不会删除任何东西。先谢谢你。使用arraycopy从阵列中删除项目

public void find(Comparable value2){ 
    Scanner sc = new Scanner(System.in); 
    Comparable value = value2; 

    if (empty() == true){ 
     System.out.println("The array is empty"); 

    } 
    else{ 
    int bsValue = Arrays.binarySearch(sa,value); 
    System.out.println("The index is: " + bsValue); 
    delete(bsValue); 
    } 
    } 

public void delete(int bs){ 
    int location = bs; 
    Comparable[] tempArray = new Comparable[sa.length -1]; 
    System.arraycopy(sa, 0, tempArray, 0, location); 
    if (sa.length != location){ 
     System.arraycopy(sa, location +1 , tempArray, location, sa.length - location - 1); 
    }  
} 
+0

小记,你不将做工作”不得不写'(empty()== true)'。你可以写'(空())'(更好的方法)。 – Maroun 2013-04-18 05:20:08

回答

2

您分配tempArray,将数据复制到它中,然后放弃引用。因此,原始数组(sa)保持原样。

想必你的意思是让sa指向新的数组:

sa = tempArray; 
+0

谢谢我在第一条评论后改变了它。它现在有效。我一直在看那个! – Neophyte 2013-04-18 05:22:53

+0

将其标记为已回答,如果有帮助 – 2013-04-18 05:24:33

0

创建深拷贝SA tempArray的一个新对象,并为您