The difference between the basic knowledge of string in Java = = and equal
The basic data type, refers to the java eight basic Data Structures ( byte,short,char,int,long,float,double,boolean ), the general comparison is used == , compared to their values.
Composite data type (Class)
==The comparison is a reference to two objects, which can be understood as an address in memory, unless they are the same new object, they are == true, otherwise, are false .
equalIs the object method in. objectis implemented internally or using == an implementation, that is, if a class has no overriding equal method, then the comparison is the address.
publicbooleanequals(Object obj) { return (this == obj); }
3. The String,Integer,Date object method in is overridden in. equal
The implementation in string, which compares the literal value.
Public Boolean equals(Object AnObject) {if( This= = AnObject) {return true; }if(AnObjectinstanceofString) {String anotherstring = (string) anobject;intn = value.length;if(n = = anotherString.value.length) {CharV1[] = value;CharV2[] = Anotherstring.value;inti =0; while(n--! =0) {if(V1[i]! = V2[i])return false; i++; }return true; } }return false; }
Why rewrite
equalMethod must be overridden
hashcodeMethod?
In the notes of the JDK source equal method, this is described in the
Note that it was generally necessary to override the {@code Hashcode} method whenever this method was overridden, so as To maintain the contract for the {@code hashcode} method, which states that equal objects must has equal hash cod Es.
equals hashcode The main purpose of the overriding method when overriding the method is to allow the Hashtable/HashSet/HashMap collection to work properly, because these collections are based on hashcode address judgments, and if you override equals without rewriting hashcode , HashMap save a key for 2 identical objects , but the corresponding 2 values, and the time is not to take out the value, the other collection class is similar, in order to avoid confusion error, so the above collection class rewrite equals must override the hashcode method.
The immutability of a string what is an object immutable?
Immutable objects are the states of an object that, after being initialized, cannot be changed throughout the lifetime of the object. To ensure that they do not change semantics in subclasses.
How are immutable objects designed?
- Setting a value method (set method) is not provided for a property
- All properties are defined as private final
- Class declared as final does not allow inheritance
Note: Without the final keyword, you can also implement an object that is immutable, using final only to display the declaration, prompting the developer and compiler to be immutable.
publicfinalclass String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ privatefinalchar value[];
First, the underlying storage of a string is based on an array of characters declared final, followed by the string class itself final . Based on these two points, you cannot write a class that inherits the string class.
Why is a string designed to be immutable?
- Security factors, Java's class loading mechanism loads classes by passing parameters (usually class names) that, under the Classpath, change the program by customizing the class-loading mechanism if the string is mutable.
- Performance factors string immutable design for performance reasons, of course, the underlying principle is the string constant pool, the immutable string to better improve performance.
- Thread safety when multithreaded access, immutable objects are thread-safe and do not require any advanced logical interpretation, and if the object is immutable, the thread cannot change it.
Six test questions
Tips One: * When two 字符串字面值 connections (add), the resulting new string is still a string literal, saved in a constant pool *
publicstaticvoidtest1() { "a1"; //当两个字符串字面值相加,得到的新字符串依然是字符串字面值,保存在常量池中 "a"1; System.out.println(a == b); System.out.println(a.equals(b)); } truetrue
TIP: When the string literal is connected to a string type variable, the resulting new string is no longer saved in the constant pool, but is created in the heap with a new string object to store. Note constants are required in a constant pool, and there is certainly no constant pool of string variables.
publicstaticvoidtest2() { "ab"; "b"; //这是一个字符串字面值和一个字符串变量 相加,得到的是一个新字符串 ,在堆中创建一个新的变量来保存 "a" + bb; System.out.println(a == b); System.out.println(a.equals(b)); } falsetrue
Tips Three: string literals are concatenated with the string type constants, and the resulting new string is still stored in the constant pool
publicstaticvoidtest3() { "ab"; //注意,这个是字符串常量 "b"; "a" + bb; System.out.println(a == b); System.out.println(a.equals(b)); } truetrue
Tips Four: not defined as final is saved in a constant pool.
/** * It is obvious that the string object referenced here by the BB constant is saved in the heap, because the string GETBB () is already stored in the heap, and the final string reference does not change the fact that string has been saved in the heap. */ Public Static void test4() {String a ="AB";//final String bb = GETBB (); actually with final string bb = new String ("B"); ///That is, return "B" creates a string object in the heap to save "b", although BB is defined as final. FinalString BB = GETBB (); String B ="a"+ BB; System.out.println (A = = B); System.out.println (A.equals (b)); }Private StaticStringGETBB() {return "B"; }--->false true
Tips Five: intern () method
This method is a native method, cannot see the source code, has the comment in the JDK.
Returns a normalized representation of a string object.
An initially empty string pool, which is privately maintained by the class string.
When the Intern method is called, if the string constant pool already contains a string equal to this string object (as determined by the Equals (Object) method), the string in the pool is returned. Otherwise, this string object is added to the pool and a reference to this string object is returned. It follows the following rules: For any two strings s and T, s.intern () = = T.intern () is true if and only if S.equals (t) is true.
//首先,变量a在栈上,保存的是“ab”的引用, //“ab”在字符串常量池中,没有在堆上创建对象 privatestatic"ab"; publicstaticvoidtest5() { "a"; "b"; //两个字符串变量相加,得到的结果字符串保存在堆中 String s = s1 + s2; System.out.println(s == a); System.out.println(s.intern() == a); System.out.println(s.equals(a)); } falsetruetrue
Tips Six:
///First, there is a string "AB" in the string constant pool, //Then, when new, a copy of the string is stored in the heap, //So the string variable a points to the "AB" string in the heap Private StaticString A =NewString ("AB"); Public Static void Test6() {String S1 ="a"; String s2 ="B";///Two string variables added, resulting string saved in heapString s = s1 + s2; System. out. println (s = = a); System. out. println (S.intern () = = a); System. out. println (S.intern () = = A.intern ()); System. out. println (S.equals (a)); }--->false false true true
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Basic knowledge of string in Java