我是Java编程的新手,我的程序遇到了麻烦。 我有一个数组,我想从中提取最大整数并将其返回到主程序。但没有使用ArrayList。 当我打印它时,我不能在这个特定的位置有0,所以我不能替换它。看看我到目前为止所做的事情,但我认为这是错误的。
public int extractMax()
{
for (int i = 0; i < size; i++)
{
if(maxInsert == Queue[i])
{
Queue[i] = null;
return maxInsert;
}
} return -1;
}
答案 0 :(得分:0)
如果数组在基元数组中,则不能指定null,您会看到如下错误:
无法从null转换为int
如果数组是一个对象数组(例如Integer),那么将它指定为null将起作用,但我建议你是否需要操作数组中使用List的条目。
例如:
List<Integer> integers = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10}));
System.out.println(integers.size());
integers.remove(new Integer(3));
System.out.println(integers.size());
会打印:
10
9
答案 1 :(得分:0)
因此,这里的逻辑是基本遍历数组的每个元素,以查看是否有一个元素大于数组中当前最大元素(从第一个元素开始)。如果找到更大的元素,则将max变量重置为此新值并继续循环。如果找到更大的元素,那么通过更新max变量就会发生同样的事情。要从数组中实际删除此元素,您可以创建一个大小小于原始大小的新数组,将所有元素复制到新数组中,并将所有元素移到最大值的右侧由左边一个。这应该是它的样子。
public int extractMax()
{
maxInsert = Queue[0];
int maxIndex = 0;
for (int i = 1; i < size; i++)//get the location of the max element
{
if(maxInsert < Queue[i])
{
maxInsert = Queue[i];
maxIndex = i;
}
}
int[] temp = new int[Queue.length - 1];
for(int j = 0; j < maxIndex; j++){ //adding elements up until the max
temp[j] = Queue[j];
}
for(int k = maxIndex; k < temp.length; k++){ //adding elements after the max
temp[k] = Queue[k+1];
}
Queue = temp; //queue is now this new array we've just made
return maxInsert;
}
答案 2 :(得分:0)
基本上,您无法在Array
对象中删除List
中的元素。因此,请创建一个新的Array
并将Queue
中的所有元素添加到新Array
除了较大的元素之外。最后,将新数组分配给Queue
。这是一个示例代码:
public int extractMax()
{
for (int i = 0; i < size; i++)
{
if(maxInsert == Queue[i])
{
removeFromArray(i);
return maxInsert;
}
} return -1;
}
private void removeFromArray(int i) {
int[] newQueue = new int[Queue.length-1];
int k = 0;
for (int j = 0; j < newQueue.length; j++,k++) {
if(i == j) {
k++;
}
newQueue[j] = Queue[k];
}
Queue = newQueue;
}