实现一个类Pair,包含:两个成员变量x和y,构造方法,重写equals
时间: 2023-05-28 15:01:19 浏览: 97
方法和toString方法。
```java
public class Pair {
private int x;
private int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Pair) {
Pair other = (Pair) obj;
return this.x == other.x && this.y == other.y;
}
return false;
}
@Override
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
}
```
测试代码:
```java
public class PairTest {
public static void main(String[] args) {
Pair p1 = new Pair(1, 2);
Pair p2 = new Pair(1, 2);
Pair p3 = new Pair(2, 1);
System.out.println(p1.equals(p2)); // true
System.out.println(p1.equals(p3)); // false
System.out.println(p1.toString()); // (1, 2)
System.out.println(p3.toString()); // (2, 1)
}
}
```
阅读全文