1

I am using the Vector2 class of the libGDX API, and if I want to check the equality of two vectors I have to do the following:

Vector2 vectA = new Vector2(0, 1);
Vector2 vectB = new Vector2(1, 1);

if (vectA.x == vectB.x && vectA.y == vectB.y) {
   return true;
}

This is very uncomfortable and I am thinking about creating an equals() method for this scenario. Which should be the better to do:

  1. Creating a wrapper for the Vector2 class with an equals(Vector2) method
  2. Creating an EqualUtil class with an equals(Vector2, Vector2) method

The first would look better (in my opinion), but it may not be a 'nice' solution while the other is much cleaner but also a bit simplistic. Different ideas also welcome.

4

4 回答 4

2

是的你应该。

在我看来,最好创建一个 Wrapper(并且您还应该覆盖hashCode()以匹配新行为)。

这样做不仅会产生更具可读性的代码,而且还允许您使用集合,例如 aHashSet或其他依赖于equals()行为的方法。

这在逻辑上也很有意义,因为您正在尝试创建一个提供特定对象数据的方法 - 有什么更好的方法来显示它而不是作为实例方法来做呢?

于 2013-01-09T09:50:13.367 回答
1

我将继续,覆盖类中的方法equals()和方法。hashCode()Vector2

来自 Joshua Bloch项目 -9

覆盖 equals 时始终覆盖 hashCode

编辑:

向下滚动到第 45 页 第 45 页:Item-9

于 2013-01-09T09:58:01.760 回答
1
public interface CheckObject(){



  public abstract boolean and(CheckObject checkobject);
}



public abstract class AbstractObject()
    implements CheckObject
{

    public AbstractObject()
    {
    }

public abstract boolean and(CheckObject checkobject);
 protected void beforeObjectChecked(Object obj)
        throws IllegalArgumentException
    {
    }


public class EqualUtil extends AbstractObject {

private int point1;
private int point2;
}
protected EqualUtil(int point1,int point2){

this.point1=point1;
this.point1=point2;
}
public  boolean and(CheckObject checkobject){
    beforeObjectChecked(checkobject);
    return(this.getPoint1()==checkobject.getpoint1() && this.getPoint2()==checkobject.getpoint2()));

}


public int getPoint1() {
    return point1;
}

public void setPoint1(int point1) {
    this.point1 = point1;
}

public int getPoint2() {
    return point2;
}

public void setPoint2(int point2) {
    this.point2 = point2;
}

现在您可以从主类中使用它

于 2013-01-09T10:39:46.727 回答
0

当原始设计者出于某种原因没有包含新行为时,Wrapper 是一种很好且易于理解的方式来添加新行为。鉴于原始 API 类只使用 java.lang.object equals 方法,创建包装器对我来说似乎是一个明智的选择。

于 2013-01-09T09:55:56.663 回答