0

再び助けが必要です。ごめん。配列から null 値を削除するにはどうすればよいですか? これが私がこれまでに得たものです。

int unikCount = 0;
String c = " ";
for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < a.length; j++) {
        if (tempAry[i].equals(tempAry[j])) {
            unikCount++;
        }
        if (unikCount > 1) {
            tempAry[j] = c;
            unikCount = 1;

        }

    }
    unikCount = 0;
}
for (i = 0; i < a.length; i++) {
    if (tempAry[i] != c) {
        unikCount++;
    }

}
System.out.println(unikCount);

for (int i = 0; i < a.length; i++) {
    for (int j = 1; j < a.length; j++) {
        if (tempAry[i].equals(tempAry[j])) {
            if (tempAry[i] == c) {
                count++;
                if (tempAry[j] != c) {
                    count++;
                    tempAry[j] = tempAry[i];

                }
            }
        }
    }

}
count = 0;
for (int i = 0; i < a.length; i++) {
    System.out.println(tempAry[i]);
}

※削除部分は「System.out.println(unikCount)」以降です。今後のヘルプに感謝します。ちなみに、hash と arraylist は使えません。

4

3 に答える 3

2

null次のように確認できます。

if ( null == someObject ) 
{
    // do things
}

配列から要素を削除して自動的に縮小する方法はありません。一時配列を使用して値を保持し、新しいサイズの配列を作成して、それらすべてのアイテムを転送する必要があります。

より効果的な方法は、Listを使用することです。

于 2013-10-04T23:22:27.547 に答える
0

ロジックを見てください(適切なインデントを使用):

if(tempAry[i].equals(tempAry[j])) {                      
    if(tempAry[i] == c) {           
       count++;
       if(tempAry[j] != c) {
           count++;
           tempAry[j] = tempAry[i];

       }
    }
}

意味がありません。なぜあなたはtempAry[j] != c if(tempAry[i] == c)をチェックするのですか?

if...else代わりに使うつもりだったの?

于 2013-10-04T23:29:51.593 に答える
0
int j = 0;
Object[] temp = new Object[a.length];
for (int i = 0; i < a.length; i++) {
    if (a[i] != null) {
        temp[j++] = a[i];
    }
}
Object[] newA = new Object[j];
System.arraycopy(temp, 0, newA, 0, j);

配列が文字列などの配列である場合は、もちろん「オブジェクト」を「文字列」に変更します。そして、「null」が空の文字列を意味する場合、ifテストは適切に変更されます。

于 2013-10-04T23:43:05.240 に答える