簡體   English   中英

如何使用循環移動數組中的每個元素?

[英]How to shift each elements in array using loops?

如果存在null,我想將數組中的每個元素向左移動。 例如

    public static void main(String[] args) {
    String asd[] = new String[5];
    asd[0] = "zero";
    asd[1] = "one";
    asd[2] = null;
    asd[3] = "three";
    asd[4] = "four;

我希望輸出是

  zero, one, three, four.

長度也應調整

我該如何使用循環? 我嘗試使用if語句檢查元素是否不為null將該值復制到另一個數組。 但我不知道如何復制是否有一個空值。

考慮到這類問題,我想您想要一個簡單的,僅基於循環和僅基於數組的解決方案,以了解其工作原理。

您必須在數組上進行迭代,並保留新插入點的索引。 最后,使用相同的索引,您可以“縮小”數組(實際上是復制到新的較小數組中)。

String[] arr = {"a","b",null,"c",null,"d"};

// This will move all elements "up" when nulls are found
int p = 0;
for (int i = 0; i < arr.length; i++) {
  if (arr[i] == null) continue;
  arr[p] = arr[i];
  p++;
}

// This will copy to a new smaller array
String[] newArr = new String[p];
System.arraycopy(arr,0,newArr,0,p);

剛剛測試了這段代碼。

編輯:

關於在不使用System.arraycopy的情況下縮小數組的可能性,不幸的是,在Java數組中,必須在實例化它們時聲明其大小,並且在此之后不能進行更改(也不能使其變大或變小)。

因此,如果您有一個長度為6的數組,並且找到2個空值,則無法將其縮小為4的長度,如果沒有創建新的空數組然后復制元素的話。

列表可以增長和收縮,並且更易於使用。 例如,帶有列表的相同代碼為:

String[] arr = {"a","b",null,"c",null,"d"};
List<String> list = new ArrayList<>(Arrays.asList(arr));
Iterator<String> iter = list.iterator();
while (iter.hasNext()) if (iter.next() == null) iter.remove();
System.out.println(list);

嘗試:

int lengthNoNull = 0;
for(String a : asd) {
    if(a != null) {
        lengthNoNull++;
    }
}
String[] newAsd = new String[lengthNoNull];
int i = 0;
for(String a : asd) {
    if(a != null) {
        newAsd[i++] = a;
    }
}

僅使用數組的一段代碼。

    String[] x = {"1","2","3",null,"4","5","6",null,"7","8","9"};
    String[] a = new String[x.length];
    int i = 0;
    for(String s : x) {
        if(s != null) a[i++] = s;
    }
    String[] arr = Arrays.copyOf(a, i);

或這個:

    String[] xx = {"1","2","3",null,"4","5","6",null,"7","8","9"};
    int pos = 0, i = 0;
    String tmp;
    for(String s : xx) {
        if(s == null) {
            tmp = xx[pos];
            xx[pos] = s;
            xx[i] = tmp;
            pos++;
        }
        i++;
    }
    String[] arr = Arrays.copyOfRange(xx, pos, xx.length);

暫無
暫無

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

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