eqluas and hashCode in Java and review summary

Java in equlas function, the default is relatively memory address, namely ==; you can override this function, you can compare the value!

https://www.cnblogs.com/dolphin0520/p/3592500.html

  String class of the equals method has been rewritten to compare whether the string string object is equal to the stored points.

  Other classes, such as Double, Date, Integer, etc., are carried out on the equals method to compare the content of the object pointed to rewrite stored are equal.

  to conclude:

  1) For ==, if applied to the basic data types of variables, which directly comparing "value" is stored are equal;

    If applied to a reference type variable, the address comparison is pointed object

  2) For the equals method, note that: equals method can not be applied to the basic data types of variables

    If there is no rewriting of the equals method, the address comparator is a reference to the object type variable points;

    Such as a String, Date, etc. based on the rewritten equals method then compares the contents of the object pointed to.

 

String of equals and hashCode function

https://www.cnblogs.com/weilu2/p/java_hashcode_equals.html

hashCode String class () and equals () method

hashCode method

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

Use hashCode () method for determining the position of an element stored in a data structure

equals () method

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

For String class can be found, if judged to be the same as two String instance, requires determination by one of these two characters in the string are the same.

 

HashSet special instructions:

In front of the HashSet attribute declaration can see a line of code, according to this we see it actually in Java HashSet is relying on the realization of the HashMap. So then the HashMap method to add elements to look for this look:

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

Here is a real logical elements stored in putVal () this method, there is no more Tieshanglai the code, the key here briefly the logic. It calls into elements hashCode () method to calculate the position of the element in the corresponding table, and then determines whether the content of this location. If this position and have an element, then the incoming call elements of equals () method with the existing elements were compared in order to determine whether two elements are the same, if not identical, it will be stored in this element table.

Sample code to verify

1, the required test User class

public class User {
	
	private String id;
	private String name;
	private String pwd;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public User(String id, String name, String pwd) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
	}
	public User() {
		super();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj) {
			return true;
		}
		boolean ret = false;
		if(this != null && obj != null && obj instanceof User) {
			User that = (User)obj;
			if(this.id.equals(that.getId())
					&& this.name.equals(that.getName())
					&& this.pwd.equals(that.getPwd())) {
				ret = true;
			}
		}
		return ret;
	}
	
	@Override
	public int hashCode() {
		int hash = 0;
		StringBuilder sb = new StringBuilder();
		sb.append(id);
		sb.append(name);
		sb.append(pwd);
		char[] charArr = sb.toString().toCharArray();
		for(char c : charArr) {
			hash = hash * 131 + c;
		}
		return hash;
	}
	
	

}

2, Equals & HashCode test class

import java.text.SimpleDateFormat;
import java.util.Date;

public class EqulasTest {

	public static void main(String[] args) throws Exception {
		String str1 = "hello";
		String str2 = "hello";
		System.err.println(str1 == str2);	// true	-> 比较内容
		System.err.println(str1.equals(str2));	// true	->比较内容
		System.err.println("hello" == "hello");	// true	->地址相同

		Integer obj1 = new Integer(1);
		Integer obj2 = new Integer(1);
		Integer obj3 = obj1;
		System.err.println(obj1 == obj2);	// false	->内存地址不同
		System.err.println(obj1 == obj3);	// true		->内存地址相同
		System.err.println(obj1.equals(obj2));	// true	->值相同
		System.err.println(obj2.equals(obj3));	// true	->值相同
		
		String dateStr = "2019-04-29 08:08:08";
		
		/*
		 * Date date = strToDate(dateStr, ""); Date date1 = strToDate(dateStr, "");
		 * System.err.println(date == date1); // false ->内存地址不同
		 * System.err.println(date.equals(date1)); // true ->值相同
		 * System.err.println(date.compareTo(date1)); // true ->值相同
		 */		
		User user1 = new User("1", "lisan", "112233");
		User user2 = new User("1", "lisan", "112233");
		User user3 = new User("2", "lisan", "112233");
		User user4 = user1;
		// 未重写User类的equals函数之前
		System.err.println(user1 == user2);			// false	-> 比较内存地址
		System.err.println(user1.equals(user2));	//	false 	-> 依然比较内存地址
		System.err.println(user1.hashCode()+"=>"+user2.hashCode());	// 366712642=>1829164700
		
		// 重写User类的equals函数之后
		System.err.println("User类的equals重写之后=>" + (user1 == user2));			// false	-> 比较内存地址
		System.err.println("User类的equals重写之后=>" + user1.equals(user2));		//	true 	-> 由于重写之后比较的是对象的各个元素值
		System.err.println( "User类的equals重写之后=>" + (user1.hashCode()+"=>"+user2.hashCode()));	// 366712642=>1829164700
		
		// 重写User类的hashCode函数之后
		System.err.println( "User类的hashCode重写之后=>" + (user1.hashCode()+"=>"+user2.hashCode()));	// 1432200454=>1432200454,相当于比较值了
	}

	/**
     * `字符串格式化为时间 
     * @param src 源字符串
     * @param format 格式化,如"yyyy-MM-dd HH:mm:ss";若为空,则使用默认格式化
     * @return
     */
    public static Date strToDate(String src, String format) {
        Date dest = null;
        src = trimNull(src);
        if (!"".equals(src)) {
            format = trimNull(format,DEFAULT_FORMAT);
            try {
                dest = new SimpleDateFormat(format).parse(src);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return dest;
    }
    
    /**
	 * 去除空格(若为null或"null"则替换为默认字符串)
	 * @param src 源字符串
	 * @param def 默认字符串
	 * @return
	 */
	public static String trimNull(String src, String def) {
		src = src == null ? "" : src.trim();
		return src.toLowerCase().equals("null") ? "" : def;
	}
	
	/**
	 * 去除空格(若为null或"null"则替换为"")
	 * @param src
	 * @return
	 */
	public static String trimNull(String src) {
		return trimNull(src, "");
	}
    
    /**
     * `时间格式化 默认(年-月-日 时:分:秒) yyyy-MM-dd HH:mm:ss
     */
    public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
}

Guess you like

Origin blog.csdn.net/baihua_123/article/details/89668814