gpt4 book ai didi

java - 从数组java中删除对象

转载 作者:行者123 更新时间:2023-12-02 03:57:31 25 4
gpt4 key购买 nike

我的练习题说“这个方法返回一个包含指定元素的数组

 // array of Objects, with the Object at the specified index removed.

// the returned array should be smaller by one and have all elements

// in the same relative location to each other. YOU MAY NOT USE

// A LIST :)

Object[] remove(int index, Object[] arr){"

到目前为止,我已经想出了这个方法,但我并不完全确定它是否有效。你们能否看一下并给我一些有关如何修复它的反馈,以便我可以正确地执行此“删除”操作。

public static remove(int index, Object[] arr){
int counter = 0;
int temp = 2;
int[] arr = {1, 2, 3, 4};
int[] second = new int[arr.length-1];

for(int i=0; i< arr.length;i++){
if(i != temp){
second[counter] = arr[i];
counter ++;

}
//return second;
}

最佳答案

public static Object[] remove(int index, Object[] array) {
Object[] newArray = new Object[array.length - 1];
for (int i = 0; i < array.length; i++) {
if (index > i) {
newArray[i] = array[i];
} else if(index < i) {
newArray[i - 1] = array[i];
}
}
return newArray;
}

关于java - 从数组java中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35285833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com