-1

クラスの割り当てを行っていますが、配列から要素を削除する方法がわかりません。ArrayUtils を使用するか、配列をリンクされたリストに変換するための提案を読みました。私はまだJavaに非常に慣れていないので、実際にこのようなことをする必要があるのか​​ 、それとももっと簡単なことを見落としているのかわかりません。また、配列内のすべての null 要素をスキップする必要があるいくつかのプロセスを完了する必要があります。私には優れた教授がいないので、コミュニケーションの試みは無駄なので、ここの誰かが助けてくれることを願っています. 私のコードは次のとおりです。関連するビットは「public void remove」で始まります。何が起こっているのかをより完全に把握するために、このクラスのすべてのコードを投稿しています。

public class WatchCollection
{   

private Watch watches[];    // an array of references to Watch objects
                            // watches[i] == null if there is no watch in position i
private int num;            // size of the array

private void init(int numberOfWatches) {
    watches = new Watch[numberOfWatches];
    for (int i=0;i<numberOfWatches;++i)
    {
        watches[i] = null;
    }
    num = numberOfWatches;
}
public WatchCollection(int numberOfWatches)
{   
    init(numberOfWatches);
}
public WatchCollection (Watch  w1)
{
    init(1);
    add(w1);            
}

// TODO Define WatchCollection (Watch w1, Watch w2) constructor
public WatchCollection (Watch w1, Watch w2)
{
}

// TODO Define WatchCollection (Watch w1, Watch w2, Watch w3) constructor
public WatchCollection (Watch w1, Watch w2, Watch w3)
{
}

public void add    ( Watch w )
{
    for(int i=0;i<num;++i)
    {
        if (watches[i]==null)
        {
            watches[i]=w;
            return;
        }
    }
}
public void remove ( Watch w )
{
    // TODO Write a code that removes Watch w if it is in the array

}

public int size()
{
    // TODO Write a code that returns actual number of watches, skip all null array elements
}

public Watch at( int index)
{
    // TODO Write a code that returns a watch with the specified index (skip all null array elements)
    // TODO Throw an exception if the index is < 0 or >= actual number of watches
    // For example, if the array contains w1 w2 null w3 w4
    // index 0 -> w1
    // index 1 -> w2
    // index 2 -> w3
    // index 3 -> w4
    // index 4 -> an exception

}

public String toString()
{
    String str="{\n";

    int index=0;
    for(int i=0;i<num;++i)
    {
        if (watches[i]!=null)
        {
            str+=" " +index++ + ": " +watches[i] + "\n";
        }
    }
    str+=" }";
    return str;      
 }
}
4

5 に答える 5

2

ArrayList要素へのインデックス付きアクセス、任意の要素を削除する機能、および動的拡張を提供する組み込みクラスです。

于 2013-06-16T18:41:54.460 に答える
0

配列の代わりに Arraylist を使用します。すでに配列がある場合は、それを A に変換します

于 2013-06-18T07:40:22.077 に答える