J2SE

xiaoxiao2021-03-06  42

1, == and Equals () difference

== Can be used for any object, it is more than the object's Reference, not the content. Compare content needs to use Equals

The default behavior of the equals () method in Java is comparing REFERENCE, so unless you override equals () in the new class, you compare or Reference, but most classes in JDK have written Equals. () The method, so it will compare the contents of the object rather than Reference.

-------------------------------------------------- -------------------------------------------------- -------------------------------

2. In Java's conditional judgment, this is not allowed (x = y), but if X and Y are Boolean type, there is no problem.

-------------------------------------------------- -------------------------------------------------- -------------------------------

3, overwriting the toString () method

Public class b {public string toString () {return "this is a";}} public class a {public static void main (string [] args) {system.out.println (new b ());}}

Output: this is a

Understand: Because the TOString method has been declared in B, it is actually overloaded to the toString method. At this time, system.out.println (Object) automatically calls the Object's toString method output.

Any Class in Java is extension from Object, there is a toString () method, system.out.println (object) will call this object's toString method by default. If you rewrive this toString in Class, rewriting this toString () Method, that is, when the output is output, the called Tositring method is defined in the class.

In fact, the parameter of System.out.Println () is String. He will convert the parameters to the String type, to rewrite the toString method, so when the new b () is converted into string, the toString function will be called. The called is the function you define.

However, it should be noted that the printed "A @ 13f5d07" is not his "address", but the class of the object and the hash value of the object.

The following is the code of the toString () method of the Object class: public string toString () {return getclass (). Getname () "@" integer.tohexstring (hashcode ());}

Where: getClass (). GetName () Returns the class name "of the object" Hashcode () Returns the hash value of the object Integer.toHexString (hashcode ()) expands the hash value of the object

So finally got this result: a @ 13f5d07

转载请注明原文地址:https://www.9cbs.com/read-54329.html

New Post(0)