我可以从我的数组中删除项目,但是当我尝试插入项目时,它会在nullpointer异常上失败。这仅在删除后发生。插入项目正常。 提前谢谢。
这确定了插入新项目的位置,以便数组保持顺序
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;
}
这使用在properPostion
中找到的索引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();
}
}
答案 0 :(得分: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();
}