-1

我可以从我的数组中删除项目,但是当我尝试插入一个项目时,它会因空指针异常而失败。这仅在删除后发生。插入项目正常工作。先感谢您。

这决定了在哪里插入新项目,以便数组保持有序

public int appropriatePosition(Comparable ap){
    int temp = top;
    if(temp == -1){
        temp = 0;
    }
    else
    {
        for(int i = 0; i <= top; i++)
        {
            if(ap.compareTo(sa[i])>0)
            {
                temp = i + 1;
            }
        }
    }
    return temp;
}

这使用在适当的位置中找到的索引

public void insert(Comparable a){

    int loc = appropriatePosition(a);
    if(full() == true)
    {
        int expandedSize = sa.length + incrementAmount;
        Comparable[] tempArray = new Comparable[expandedSize];
        for(int i= 0; i < sa.length; i++)
        {
            tempArray[i]= sa[i];
        }
        sa  = tempArray;
    }
    for(int i = top; i >= loc; i--)
    {
        sa[i+1] = sa[i];
    }
    sa[loc] = a;
    top++;
}

public void find(Comparable value2){    
    Comparable value = value2;

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


// This method deletes a given value from the array

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);
         sa = tempArray;
         print();
     }      
}
4

1 回答 1

0

我找到了。谢谢您的帮助。删除后我忘了减少顶部。

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);
         sa = tempArray;
         top--;
         print();
     }      
于 2013-04-18T06:29:21.820 回答