Java Object General Method

Copyright: Welcome ssm build personal blog https://www.yanzhaochang.top all copyright wait bloom all https://blog.csdn.net/qq_42081709/article/details/90108956

Object Method Overview

  public boolean equals(Object obj)

  public native int hashCode()

  protected native Object clone() throws CloneNotSupportedException

  public String toString()

  public final native Class<?> getClass()

  protected void finalize() throws Throwable {}

  public final native void notify()

  public final native void notifyAll()

  public final native void wait(long timeout) throws InterruptedException

  public final void wait(long timeout, int nanos) throws InterruptedException

  public final void wait() throws InterruptedException

  一 equals()

    a) Properties:

        1. reflexive

   x.equals(x); // true

        2. symmetry

   x.equals(y) == y.equals(x); // true

        3. transitive

   if (x.equals(y) && y.equals(z)){
      x.equals(z); // true;    
   }

        4. Consistency

      x.equals(y) == x.equals(y); // true

        Multiple calls equals () method results unchanged

        The non-null type

   x.equals(null); // false; 

          equlas parameter is null, then the result is necessarily false

     b) equals method of Object source

     public boolean equals(Object obj) {
        return (this == obj);
     }

          In fact, it equals itself or use the == comparison,

             It is the same for comparing the contents of the basic data types

             HashCode data type is the same for comparison reference, i.e., the comparison is not the same object

         There must be two objects equals comparisons.

    c) Method override equals Custom 

        Example:

    class People {
	private String id;
	private String name;
	private Integer age;
        People(String id,String name){
            this.id = id;
            this.name = name;
        }        
        @Override
	public int hashCode() {
	 final int prime = 31;
	    int result = 1;
	    result = prime * result + ((age == null) ? 0 : age.hashCode());
            result = prime * result + ((id == null) ? 0 : id.hashCode());
	    result = prime * result + ((name == null) ? 0 : name.hashCode());
	    return result;
    	}
    	@Override
	public boolean equals(Object obj) {
	    if (this == obj) //先使用==判断两个对象地址是否相同,相同的话就返回true。
	        return true;
	    if (obj == null) //如果比较的对象是null,直接返回false
		return false;
	    if (getClass() != obj.getClass()) 判断两个兑现的类型,相同就继续执行,否则返回false
		return false;
	    People other = (People) obj;//下面的步骤就是判断两个对象的各个属性,不相同返回false,所有属性都相同后返回true
	    if (age == null) {
		if (other.age != null)
	            return false;
	    } else if (!age.equals(other.age))
		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;
	}
    }

   

note:

            Rewrite equals () when we must override the hashCode ()

            Example:

            If there are two objects

                  People  p1 = new People("1","张三");

                  People  p2 = new People("1","张三");

            If only rewriting without overwriting equals hashcode, then people Object class is the default hashcode method, since the default hashcode method according to the memory address of the object by hashing come apparent p1! = P2, so that both It is not necessarily the same hashcode

            However, if you override the equals, and returns p1.equals (p2) true, according to the rules of hashcode, two hash values ​​of the objects had to be equal, so here are contradictory, and therefore override the equals method must override hashcode method 

            hashcode rules:   

                1. The same two objects, hashcode necessarily the same

                    Two different objects, hashcode not necessarily different

                2. The same hashcode, two objects are not necessarily the same

                    hashcode range, two objects must be different

 比较详情--->== and equals the difference 

 

 Two hashCode () method

        1. hashCode () Returns a hash value, and equals () is used to determine whether two objects are equivalent, the equivalent of two objects necessarily the same hash value, but the same hash value is not necessarily equivalent to two objects

            So the above mentioned must reach the hashCode () method when the cover equals () methods, to ensure that the two hash values ​​are the same the same object.

    People p1 = new People("1","张三");
    People p2 = new People("1","张三);
    System.out.println(p1.equals(p2)); // true
    HashSet<People> set = new HashSet<People>();
    set.add(p1);
    set.add(p2); 
    System.out.println(set.size());   // 2

         At this time, we hope the two objects are the same, because the set is a collection of add only object <hashcode this time People do not realize the method, because the hash value of the two objects are different, resulting in the addition of two equivalent Object.

       2. The hash function should preferably have a uniform, i.e. unequal objects to be evenly distributed over all possible hash values. This requires that the value of the hash function to put all the fields are taken into account. Each domain can be treated as a bit of R band, then make up a R integer hexadecimal. R 31 and generally, as it is an odd prime number, if it is an even number, when an overflow occurs multiplication, data will be lost, since the one is multiplied by 2 corresponds to the left.

           31 is multiplied by a number of shift and subtraction can be converted to: 31 * x == (x << 5) -x, the compiler will be automatically optimized.

  @Override
  public int hashCode() {
    int result = 17;
    result = 31 * result + x;
    result = 31 * result + y;
    result = 31 * result + z;
    return result;
  }

Three toString () method

        People 70dea4e default return this form @, namely the class name @ hash code unsigned hexadecimal 

  public class People{	
    private String id;    
    public People(String id) {
        this.id= id;
    }    
    public static void main(String[] args) {
	System.out.println(new People("1").toString());
    }
  }

 

Four clone method

     1. The method can not be rewritten is protect    

     2. Copy quote

  Person p = new Person(23, "zhang");  
  Person p1 = p;

     3. Copy Objects

  Person p = new Person(23, "zhang");  
  Person p1 = (Person) p.clone();

     4. shallow copy: reference the same object without rewriting the clone (), call the Object.clone ()

     5. deep copy: reference the same object, to achieve Cloneable interface override method.

  public class People implements Cloneable{
    private String id;
    public Object clone() {
    	People p = null;
    	try {
	    p = (People) super.clone();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    	return p;
    }
  }

 

 

Guess you like

Origin blog.csdn.net/qq_42081709/article/details/90108956