以下是要求:
添加到IntList
:
resize
方法:为IntList写一个resize方法,使方法的大小加倍。如上所述
在第7章中,您不能简单地调整数组大小,必须实例化一个增加的新数组
size,复制从旧数组到新数组的所有内容,然后将旧数组引用分配给
新阵列。对于这个应用程序,resize方法只能由子类使用,但它是
IntList类具有良好的功能。 equals
方法:为IntList编写一个equals方法。记得使用Object参数!
如果两个IntList对象具有相同数量的元素,则应将它们视为相等
(不考虑容量)并且每个索引中的每个元素都匹配值。 clone
方法:为IntList编写克隆方法。请记住,克隆方法不应该
有参数,应该返回一个Object。您的克隆方法需要进行深层复制
返回的对象不包含任何别名。(我只需要equals
的帮助,如果您能检查我的clone
和resize
是否按预期工作,我将不胜感激。
public class IntList
{
private int[] list;
private int numElements;
/**
* Constructor -- creates an integer list of a given size.
* @param size the number of elements in the list
*/
public IntList(int size)
{
list = new int[size];
numElements = 0;
}
/**
* Adds an integer to the list. If the list is full,
* prints a message and does nothing.
* @param value the value to add
*/
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else
{
list[numElements] = value;
numElements++;
}
}
/**
* Retrieves the integer at a specified index
* @param index the index to retrieve
* @return the integer at that index
*/
public int getNum(int index)
{
return list[index];
}
/**
* Sets the integer at a specified index
* @param index the index to change
* @param num the number to assign at index
*/
public void setNum(int index, int num)
{
list[index] = num;
}
/**
* returns the number of elements in the list
* @return number of elements
*/
public int getNumElements()
{
return numElements;
}
/**
* returns the length (capacity) of the list
* @return length
*/
public int getLength()
{
return list.length;
}
/**
* Returns a string containing the elements of the list with their
* indices.
* @return the String version of the IntList
*/
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
// Add resize, equals and clone, and their javadocs
public void rezise()
{
int [] temp = new int[list.length*2];
for(int i = 0; i<numElements; i++)
{
temp[i]=list[i];
setNum(i,getNum(i));
}
}
public boolean equals(Object o)
{
IntList a = (IntList)o;
if(a.numElements != numElements)
return false;
for(int i = 0; i < numElements; i++)
{
list[i]!=a.list[i];
}
}
public Object clone()
{
IntList a = new IntList(numElements);
for(int i = 0; i<numElements; i++)
{
a.add(list[i]);
}
return a;
}
}
答案 0 :(得分:1)
你是否使用吸气剂(你的老师的说法是可疑的)与equals
必须如何工作有些无关。首先,请考虑一般equals
的含义:如果此true
等于另一个指定的IntList
,则返回IntList
。
好的,那么现在两个IntList
相等是什么意思?好吧,就像你的描述一样:
n
,this.list[n]
必须等于o.list[n]
。这些都是非常简单的规则。一般来说,一旦你制定了这些规则,就应该更容易将它们从英语翻译成Java。
您可以直接访问字段(例如o.numElements
)或通过getter(例如o.getNumElements()
),无论您是否这样做都会轻微影响您的语法,但通常对您的逻辑没有影响。< / p>
在许多情况下(虽然肯定不是全部)如果你的类不是final
,你会想要使用getter,因为派生类可能有不同的实现,你想要使用那些实现而不是直接字段访问可以绕过它们。