此方法是否创建精确的副本?(java中的复制方法)

此方法是否创建精确的副本?(java中的复制方法),java,testing,Java,Testing,我有一个家庭作业要在other中为下面的方法编写一个测试,以显示使用此方法创建的对象及其副本是相等的 /** * Creates a new object that is a duplicate of this instance of * Parameter. * <p> * The duplication is a "deep copy" in that all values contained in the * Parameter are themselves d

我有一个家庭作业要在other中为下面的方法编写一个测试,以显示使用此方法创建的对象及其副本是相等的

   /**
 * Creates a new object that is a duplicate of this instance of
 * Parameter.
 * <p>
 * The duplication is a "deep copy" in that all values contained in the
 * Parameter are themselves duplicated.
 * 
 * @return The new duplicate Parameter object.
 */
public Parameter copy( )
{
    Parameter result = new Parameter( );
    result.setName( getName( ) );
    for ( int index = 0; index < getNumberOfValues( ); index++ )
    {
        result.addValue( getValue( index ).copy( ) );
    }
    return result;
 }
但这种方法似乎不能创建和精确复制param。 请你给我引路好吗

这是值的复制方法:

   /**
 * Creates a new Value object that is a duplicate of this instance.
 * 
 * @return The new duplicate Value object.
 */
public Value copy( )
{
    Value newValue = new Value( );
    newValue.setName( getName( ) );
    return newValue;
}

您的参数类需要一个equals方法()。如果没有此选项,java将基于引用运行相等(Object.equals()的默认行为),因此您可以观察到

您的equals方法可能如下所示:

public boolean equals(Object o)
{
    Parameter p = (Parameter)o;
    return this.getName().equals(p.getNames) && this.getNumberOfValues() == p.getNumberOfValues() &&B this.values().equals(p.values());
}

对象
()的equals方法明确指出,引用需要引用同一个对象才能返回true。在您的情况下,复制方法正确地创建了一个新参数,然后创建了一个新值,以便创建复制对象。因此,现有的
equals()
方法将始终返回false


为了正确地进行测试,您需要按照注释中的说明进行操作,即创建一个新的equals()方法,该方法将覆盖对象类中现有的方法,包括参数类和值类。您的方法应该测试每个对象的内容(每个对象中的名称)是否相同,或者您认为适合您的应用程序的任何其他语义。

是否重写了equals()?值类的复制方法是否与参数中的克隆方法类似?我的意思是,创建一个新实例并将值赋给新对象。有趣的是,它显示这两个对象不相等的事实证明了OP确实创建了深度副本而不是浅层副本。它已经从object继承了一个equals()方法;OP需要覆盖它。
public boolean equals(Object o)
{
    Parameter p = (Parameter)o;
    return this.getName().equals(p.getNames) && this.getNumberOfValues() == p.getNumberOfValues() &&B this.values().equals(p.values());
}