这个测试,为什么总是false

2019-03-25 13:51|来源: 网路

//TPoint.java
/*
 This is just a trivial "struct" type class --
 it simply holds an int x/y point for use by Tetris,
 and supports equals() and toString().
 We'll allow public access to x/y, so this
 is not an object really.
 */
public class TPoint {
	public int x;
	public int y;

	// Creates a TPoint based in int x,y
	public TPoint(int x, int y) {
		// questionable style but convenient --
		// params with same name as ivars

		this.x = x;
		this.y = y;
	}

	// Creates a TPoint, copied from an existing TPoint
	public TPoint(TPoint point) {
		this.x = point.x;
		this.y = point.y;
	}

	// Standard equals() override
	public boolean equals(Object other) {
		// standard two checks for equals()
		if (this == other) return true;
		if (!(other instanceof TPoint)) return false;

		// check if other point same as us
		TPoint pt = (TPoint)other;
		return(x==pt.x && y==pt.y);
	}

	// Standard toString() override, produce
	// human-readable String from object
	public String toString() {
		return "(" + x + "," + y + ")";
	}
}


import java.util.HashSet;


public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TPoint a =new TPoint(0,1);
		TPoint b =new TPoint(0,1);
		HashSet<TPoint> setA = new HashSet<TPoint>();
		HashSet<TPoint> setB = new HashSet<TPoint>();
		setA.add(a);
		setB.add(b);
		boolean res = setA.equals(setB);
		System.out.println(res);
		
		
	}

}



问题补充:
redstarofsleep 写道
你只重写了TPoint的equals方法,但是你调用的是Hashset的equals方法,Hashset的equals方法你并没有重写哦


但是我不用TPoint,而用awt的Point 就能通过。

import java.awt.Point;
import java.util.HashSet;


public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Point a =new Point(0,1);
		Point b =new Point(0,1);
		HashSet<Point> setA = new HashSet<Point>();
		HashSet<Point> setB = new HashSet<Point>();
		setA.add(a);
		setB.add(b);
		boolean res = setA.equals(setB);
		System.out.println(res);
		
		
	}

}




问题补充:如果不用 这个TPoint
而用awt.Point 就能通过
这是为什么呢
import java.awt.Point;
import java.util.HashSet;


public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Point a =new Point(0,1);
		Point b =new Point(0,1);
		HashSet<Point> setA = new HashSet<Point>();
		HashSet<Point> setB = new HashSet<Point>();
		setA.add(a);
		setB.add(b);
		boolean res = setA.equals(setB);
		System.out.println(res);
		
		
	}

}

相关问答

更多