重写toString和equals方法
section 1 重写toString方法
源码:
/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Object类中toString()方法默认返回对象的 类名+@+地址值
如果需要根据个人需求返回一定格式的输出结果,就需要重写toString()方法
示例:
package yufatangTest;
import java.util.Objects;
/**
* equals和hashcode重写
* */
public class EQ {
private int id;
private int age;
private String addr;
public EQ(int id, int age, String addr) {
this.id = id;
this.age = age;
this.addr = addr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
// @Override
// public String toString(){
// return "{" +
// "id = {" + id + "}, " +
// "age = {" + age + "}, " +
// "addr = {" + addr + "}" +
// "}";
// }
}
test类:
public static void main(String[] args) {
EQ eq = new EQ(2, 4, new String("dsa"));
EQ eq1 = new EQ(2, 4, "dsa");
System.out.println(eq);
System.out.println(eq1);
}
输出:
yufatangTest.EQ@1540e19d
yufatangTest.EQ@677327b6
重写toString方法
@Override
public String toString(){
return "{" +
"id = {" + id + "}, " +
"age = {" + age + "}, " +
"addr = {" + addr + "}" +
"}";
}
输出:
{id = {2}, age = {4}, addr = {dsa}}
{id = {2}, age = {4}, addr = {dsa}}
section 2 重写equals方法:
equals方法官方文档解释
equals() From Class Object
public boolean equals(Object obj)
Indicates whether some other object is “equal to” this one.
The equals
method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value
x
,x.equals(x)
should returntrue
. - It is symmetric: for any non-null reference values
x
andy
,x.equals(y)
should returntrue
if and only ify.equals(x)
returnstrue
. - It is transitive: for any non-null reference values
x
,y
, andz
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
should returntrue
. - It is consistent: for any non-null reference values
x
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
, provided no information used inequals
comparisons on the objects is modified. - For any non-null reference value
x
,x.equals(null)
should returnfalse
.
The equals
method for class Object
implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x
and y
, this method returns true
if and only if x
and y
refer to the same object (x == y
has the value true
).
Note that it is generally necessary to override the hashCode
method whenever this method is overridden, so as to maintain the general contract for the hashCode
method, which states that equal objects must have equal hash codes.
-
Parameters:
obj
- the reference object with which to compare. -
Returns:
true
if this object is the same as the obj argument;false
otherwise. -
See Also:
equals() From Class Objects
public static boolean equals(Object a, Object b)
Returns true
if the arguments are equal to each other and false
otherwise. Consequently, if both arguments are null
, true
is returned and if exactly one argument is null
, false
is returned. Otherwise, equality is determined by using the equals
method of the first argument.
-
Parameters:
a
- an objectb
- an object to be compared witha
for equality -
Returns:
true
if the arguments are equal to each other andfalse
otherwise -
See Also:
【equals(A, B)允许A,B为null】
equals源码:
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
equals重写前后 比较:
在Objec类中,equals源码比较的是两个对象的地址,功能完全等同与 ==
。
某些情况下,需要比较两个对象的值是否相同,不要求地址相同,比如:
public static void main(String[] args) { EQ eq = new EQ(2, 4, new String("dsa")); EQ eq1 = new EQ(2, 4, "dsa"); System.out.println(eq == eq1); System.out.println(eq.equals(eq1));}
直接调用equals比较两者结果如下
falsefalse
重写equals:
@Override public boolean equals(Object obj) {
// 1、 比较地址
if ( this == obj ) {
return true;
}
//2、 比较类型
if( this.getClass() != obj.getClass() ) {
return false;
}
//判空
if( null == obj ) {
return false;
}
EQ eq = (EQ)obj;
//3、比较值
if( eq.id == this.id && eq.age == this.age && Objects.equals(this.addr, eq.addr) ) {
return true;
} else {
return false;
}
}
执行结果:
false
true