JAVA常用方法及其常用重写

.equals

判断两个对象的是否完全相同(地址是否相同)
未重写时和“==”一样
代码:

	System.out.println(p1.equals(p2));

标准重写:

	public boolean equals(Object obj) {
		if (this == obj)//是否是同一地址
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())//是否是同一类型
			return false;
		
		Product other = (Product) obj;//上转型对象强制转化为实际子类
	if (Double.doubleToLongBits(count) != Double.doubleToLongBits(other.count))//高精度对比double类型
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

重写:

public class Product implements Comparable<Product> {
	String id;
	String name;
	int count;
	public Product(String a, String b, int c) {
		id = a;
		name = b;
		count = c;
	}
	public boolean equals(Product other) {
		if (this.getClass() != other.getClass())
			return false;
		else if (!this.id.equals(other.id))
//等于(this.id.equals(other.id)==false)
			return false;
		else if (!this.name.equals(other.name))
//等于(this.name.equals(other.name)==false)
			return false;
		else if (this.count != other.count)
			return false;
		else
			return true;
	}

}
posted @ 2021-10-27 14:34  kingwzun  阅读(54)  评论(0编辑  收藏  举报