2016-04-08 5 views
-1

ArrayListはこの仕事をはるかに単純化しますが、これは配列のためです。どのように特定の配列要素をnullに設定し、それらの要素を配列の末尾に移動するのですか?

これは、これまでの私の方法です:

public boolean remove(String name) { 
    int temp = 0; 
    for (int i = 0; i<counter; i++) { 
     if (friends[i].equals(name)) { 
      friends[i]=null; 
      for (int j = i; j > counter; j++) { 
       friends[j] = friends[j+1]; 
      } 

      return true; 
     } 
    } 

    return false; 
} 

私が望む結果は次のとおりです。

String[] friends = {"Sean", "James", "Andrew", "Garfield", "Patrick"}; 
myfriends.remove("James"); 
System.out.println(Arrays.toString(friends)); 

コンソール出力:Sean, Andrew, Garfield,Patrick, null

答えて

1

デバッガを使用することが有用であろう場所です。

j > counterj < counterに変更し、最後にfriends[counter-1] = null;と設定します。最初に行う設定はfriends[i] = null;で、上書きすることはありません。

注:重複していないことを前提としています。

+1

ハハ! ofcそれはj JohnBanana

+0

@ JohnBananaデバッガでは、コードが決してループに入っていないことがわかります。 –

+0

ループに入ることはありません。 – JohnBanana

関連する問題