【Java】JavaBean與Object

<pre name="code" class="java">//====================JavaBean======================
class Point implements Comparable<Point>,Serializable{
	private static final long LEVEL = 20150701;//本碼講版本
	/*
	 * 版本號
	 * 如不加,序列化的時候會自動生成,這種方式嚴格的控制兼容性,只要類發生改變
	 * 則版本號就會改變,反序列化失敗
	 * 如果明確指定版本號,當類發生改變但版本號相同時,則會使用兼容模式,求同存異
	 * 原來對象有的屬性,現在還有的就還原
	 * 原來對象有的屬性,現在沒有的就忽略
	 * 原來對象沒有的屬性,現在有的則使用默認值
	 */
	private static final long serialVersionUID = 1L;
	//關鍵字:transient 聲明瞭該關鍵字的屬性將不會被序列化
	private transient int x;
	private int y;

	public Point(){
		this(0,0);
	}
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}
	/*
	 * * hashcode()方法有以下注意事項:(hashcode的用於散列表數據結構計算存放位置)
	 * 1、若一個類重寫了equals方法,那麼就應當重寫hashcode()方法。
	 * 2、若兩個對象的equals方法比較爲true,那麼它們應當具有相同的hashcode值。
	 * 3、對於同一個對象而言,在內容沒有發生改變的情況下,多次調用hashCode()方法應當總是返回相同的值。
	 * 4、對於兩個對象equals比較爲false的,並不要求其hashcode值一定不同,但是應儘量保證不同,這樣可以提高散列表性能。
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + x;
		result = prime * result + y;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		// 重寫equals方法準則見文檔:
		// 1、自反性 2、對稱性xy yx 3、傳遞性xy yz xz 4、一致性參數不變時多次調用應一致
		if (obj == null) {
			return false;
		}
		if (this == obj) {// 自反性
			return true;
		}
		if (obj instanceof Point) {
			Point point = (Point) obj;
			return point.x == this.x && point.y == this.y;
		} else
			return false;
	}

	@Override
	public String toString() {
		return "(" + x + "," + y + ")";
	}

	// 返回值負整數、零或正整數,根據此對象是小於、等於還是大於指定對象
	@Override
	public int compareTo(Point point) {
		int l1 = YaoUtils.sqrtInt(this.getX(), 2)
				+ YaoUtils.sqrtInt(this.getY(), 2);
		int l2 = YaoUtils.sqrtInt(point.getX(), 2)
				+ YaoUtils.sqrtInt(point.getY(), 2);
		return l1 - l2;
	}
	//@Test
	public void prinPoint() {
		// test toString()
		Point point = new Point(1, 2);
		System.out.println(point);
	}

	//@Test
	public void testEquals() {
		Point point = new Point(1, 2);
		Point point1 = new Point(1, 3);
		System.out.println(point.equals(point1));
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章