【问题标题】:Java: Invoking a Class-type Array to Test for EqualityJava:调用类类型数组来测试相等性
【发布时间】:2016-12-02 02:56:30
【问题描述】:

我正在开发一个程序,该程序首先采用偶数数组,然后依次创建第二个 (x, y) 坐标数组。然后,必须通过比较数组中每个点的 x 坐标和 y 坐标来将调用 PointArray 与参数 PointArray 进行比较。我从概念上知道我必须对每个数组进行排序并使用 indeces 和定义的 equals 方法比较每个点,但是我不知道如何引用调用类类型数组的一个点,而不是作为一个参数。

private double x;
private double y;

public Point(double x_coord, double y_coord)
{
    x = x_coord;
    y = y_coord;
}

public boolean equals(Point anotherPoint)
{
    if(x == anotherPoint.x && y == anotherPoint.y)
    {
        return true;
    }
    return false;
}
int count;
private Point[] points = new Point[count];

public PointArray(double[] doubleArray)
{
    count = (doubleArray.length) / 2;
    if(doubleArray.length % 2 == 0)
    {
        count = (doubleArray.length) / 2;
        for(int i = 0, j = 0; i < count; i++, j += 2)
        {
            double x = doubleArray[j];
            double y = doubleArray[j + 1];
            points[i] = new Point(x, y);
        }
    }
    else
    {
        System.out.println("Error: The given array must be even.");
    }
}
public boolean equals(PointArray anotherPointArray)
{
    double x = 0;
    double y = 0;
    double xAnother = 0;
    double yAnother = 0;
    Point newPoint = new Point(x, y);
    Point newAnotherPoint = new Point(xAnother, yAnother);
    anotherPointArray.sort();
    anotherPointArray.newPoint;
    for(int i = 0; i < points.length; i++)
    {
        for(int j = 0; i < anotherPointArray.length; j++)
        {
            if(newPoint.equals(newAnotherPoint))
            {
                return true;
            }
        }
    }
    return false;
}

编辑:澄清一下,我的问题是我不知道如何使用 PointArray 对象设置 Point equals 方法。

【问题讨论】:

  • 你的意思是你不知道如何在equals 函数中访问你的points 数组??
  • @J.Baoby 你问的是哪个equals?如果您的意思是等于(PointArray anotherPointArray),那么是的,我遇到了麻烦。但我要问的是如何声明这两个数组。例如,我认为“testPointArray1.equals(testPointArray2)”将是我调用该方法的方式,在这种情况下 anotherPointArray 是 testPointArray2。但是,布尔值上下文中的 tesrPointArray1 是什么?

标签: java arrays class equals


【解决方案1】:

当你调用对象上的方法时:

something.myMethod(argObject);

myMethod 中,您可以将something(调用该方法的对象)称为this-object。 我希望this tuto 比文字更能证明这一点。

【讨论】:

  • 我尝试使用 this 对象进行如下设置。程序运行,但它总是输出为假。 public boolean equals(PointArray anotherPointArray) { double x = 0;双 y = 0; for(int i = 0; i
  • 问题是在for循环中你说“如果数组this.points等于otherPointArray.points,则返回true,另一个PointArray的数组”。两个数组将被定义为相等,不是如果它们具有相同的内容,而是如果它们实际上是相同的(因此它们指向相同)。
  • 这有点像文件:如果你复制一个文件,你就将文件的内容(硬盘上的所有位)复制到其他地方。对于您的系统,这将导致两个不同的文件,即使它们具有相同的内容并且即使它们具有相同的名称,因为它们将指向硬盘驱动器上的不同位置。但是,例如,如果您有一个文件条目(硬盘驱动器上的位),并且以一种方式您设法为同一文件创建另一个条目(因此指向相同的内存位置,相同的位),那么系统会告诉您它是指向同一个位置的同一个文件
猜你喜欢
  • 2011-01-15
  • 2011-12-24
  • 1970-01-01
  • 2019-10-09
  • 2010-10-02
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多