簡體   English   中英

從數組java中刪除對象

[英]remove object from an array java

我的實踐問題說:“此方法返回具有指定元素的數組

 // 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;
}

除了index元素之外,您必須將所有元素復制到一個新array並返回該array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM