我正在完成一个类分配,但我不确定如何从数组中删除一个元素。我已经阅读了使用 ArrayUtils 或将数组转换为链表的建议。我对 Java 还是很陌生,所以我不确定我是否真的需要做这样的事情,或者我是否忽略了一些更简单的事情。我还需要完成几个需要跳过数组中所有空元素的过程。我没有一个很好的教授,沟通尝试是徒劳的,所以我希望这里有人能提供帮助。我的代码如下。相关位从“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;
}
}