Java Immutable classes

Source: Internet
Author: User

is the 0.final modified class an immutable class?

A: No. The final decorated class is called an inheritable class. There is no relationship between the two. That is, the class name of the immutable class can be either final or not.

1. What are the characteristics of immutable classes? That is, what are immutable classes?

A: The feature is that once an instance of the class is created, the instance content (state) cannot be modified. A typical class is a string in Java.

2. Since string is an immutable class, why can it be re-assigned and change its contents?

A: string is really designed to be immutable, but the re-assignment is not a change to the string a object; You can see that the 7th sentence would have changed the book to lowercase. But not at last. Reference types in Java are managed by reference variables to the structure of the object. Re-assignment simply alters the position of the object's reference (as seen by the hashcode above).

The difference between the new and "" and + three usages of 3.String;

A: New will open up content in the heap, "" will be cached in the string constant pool. + The ToString method is called implicitly. Stitching the same string will not re-open memory

Just remember to compare strings with equals. But an in-depth understanding of this problem will be of great benefit to our optimization program. Note String overrides the Equals method, which returns true if the Equals object content is the same.

= = More Strictly, it requires the object reference to be the same.

Right-click (1) "" is the same as the content of the same object, which is due to the caching role of Java string pool. The JVM will have the contents of "" within the pool, unless the new one is displayed, or if there is any in the pool, there is a = = B in the above example; No, just create another one in the pool.

(2) New string, even if the same content is different objects. Known by c = = d.

(3) New objects and "" are not the same object, even if the content is the same.//It is obvious that this sentence may have a misunderstanding, "" The content of some books called constant pool, constant pool is compiled to determine the content of the constant pool is not only the string type,

This means that the constant pool does not hold objects but constants. Essentially objects and constants are the same in memory,

(4) by a = = e, c== e can be seen as long as new is different. String concatenation is also first found in the pool.

What is the difference between a 4.final decorated base type and a reference type?

A: The final modifier basic type variable is immutable, and the reference type is modified, because it simply saves a reference, final only guarantees that the address of the reference does not change, that is, the same object is referenced all the time, the object content is changed or not.

Note The final modifier refers to the difference between a type variable and an immutable class.

One is the same as the reference, and one is the object of the reference.

5. How do you implement immutable classes?

Answer: refer to String.

Using private final to decorate the class's field//note that the field is good if it is a basic type, and if it is a reference type to ensure it is immutable, it may cause the creation of immutable classes to fail.

Filed the reference type to be a base type or non-mutable class

A parameter constructor is provided to initialize the field based on the parameters passed in.

Only provides getter methods for this class, does not provide setter methods

Rewrite the hashcode and equals methods if necessary

The program comes from << crazy java>>

className {PrivateString FirstName; PrivateString LastName;  PublicName () {} PublicName (String firstName, String lastName) { This. FirstName =FirstName;  This. LastName =LastName; }     Public voidsetfirstname (String firstName) { This. FirstName =FirstName; }     PublicString Getfirstname () {return  This. FirstName; }     Public voidsetlastname (String lastName) { This. LastName =LastName; }     PublicString Getlastname () {return  This. LastName; }} Public classPerson {Private Finalname name;  PublicPerson (name name) { This. Name =name;//(1) this.name = new name (Name.getfirstname (), Name.getlastname ()); }     PublicName GetName () {returnname;//(2) return new name (Name.getfirstname (), Name.getlastname ());
} Public Static voidMain (string[] args) {Name n=NewName ("Wukong", "Sun"); Person P=NewPerson (n); System.out.println (P.getname (). Getfirstname ());//WukongN.setfirstname ("Bajie"); System.out.println (P.getname (). Getfirstname ()); //Bajie }}

You can see that the filed of the person class is a reference type and can change its state in the name class. So the person class doesn't form an immutable class.

The book provides a way to change the person class to an immutable class

The two sentences (1) (2) are treated with an anonymous object.

The original version passes the name class to change the field in the person class and then returns the changed object from the constructor of the Personl class. Therefore, the object that the filed points to is susceptible to change by the name class.

Instead of being an anonymous object, returning from the constructor of the person class is the temporarily created name object, whether you change FirstName or LastName, and he just changes the FirstName of the N point.

The reader can add the previous line and the following line in the N.setfirstname

System.out.println (N.getfirstname ());

Will find a different before and after.

This means that the name object that the N points to is indeed changed.

and the name of P does not change.

Note: The filed of N is two string, and the filed of P is a name type.//class is also an object

The following defines an immutable class address----from Crazy Java

/**The reference type of the private final base data type or the immutable class provides a parameter constructor that initializes the field based on the parameters passed in to only provide getter methods for that class, and does not provide setter methods if necessary to override the Hashcode and Equals methods */ Public classAddress {Private FinalString Detail; Private FinalString postcode;  PublicAddress () {//It is generally recommended to provide a parameterless constructor if the class has written a parametric constructor         This. Detail = "";  This. Postcode = ""; }         PublicAddress (String detail, string postcode) { This. Detail =detail;  This. Postcode =postcode; }         PublicString Getpostcode () {return  This. Postcode; }     PublicString Getdetail () {return  This. Detail; }         Public Booleanequals (Object obj) {if( This==obj) {            return true; }        if(obj! =NULL&& Obj.getclass () = = Address.class) {Address ad=(Address) obj; if( This. Getdetail (). Equals (Ad.getdetail ())&& This. Getpostcode (). Equals (Ad.getpostcode ())) {                    return true; }        }        return false; }         Public inthashcode () {returnDetail.hashcode () + postcode.hashcode () * 31; }}

The field of the address class cannot be modified because the method setter method is not provided;

So is it possible to make immutable classes as long as the setter method is not provided?
No, private final can guarantee that the field of an instance created by an immutable class is not altered and not accessed by the outside world.

6. The instance state of an immutable class does not change, such instances can be safely shared with other objects associated with them, and can be safely shared by multiple threads, and in order to conserve memory space, instances of immutable classes should be reused as much as possible, avoiding the repetition of creating instances with the same property values. So how to implement caching technology? There are a number of caching techniques, with arrays as cache pools to implement immutable classes of a cache instance.

/*** This program uses an array to emulate the cache pool * The Cacheperson class can control the number of Cacheperson objects generated and can only be obtained by valueof () * If an object is used only once, it is not necessary to use the cache; * If an object is used frequently, caching is necessary . * Java.lang.Integer adopts the same strategy, if the new object is used, each time is entirely new; if valueof is used , the cache*/classCacheperson {Private Static intMax_size = 10; //using the array cache    Private Staticcacheperson[] Cache =NewCacheperson[max_size]; //record the location of the cache instance in the cache: Cache[pos-1] is an instance of the new cache    Private Static intpos = 0; Private FinalString name; //Private constructor, outer class cannot construct object    PrivateCacheperson (String name) { This. Name =name; }         PublicString GetName () {returnname; }//once the constructor is encapsulated, there must be a public method to create the object//static is necessary because creating an object can only be a class method     Public StaticCacheperson valueof (String name) {//traversing a cached instance         for(inti = 0;i < max_size; i++{If you have the same instance, return the instance directlyif(Cache[i]! =NULL&&cache[i].getname (). Equals (name)) {                returnCache[i]; }        }        //Cache is full        if(pos = =max_size) {            //overwrite the first instance of the cache by placing the object you just generated at the beginning of the cache poolCache[0] =NewCacheperson (name); POS= 1; } Else {            //newly created instances are cached, pos+1 .cache[pos++] =NewCacheperson (name); }        returnCache[pos-1]; }    /*here the Equals method is often used best to write down: To determine whether two objects are equal = = for the basic data type as long as the value is equal; For reference variables, only true when pointing to the same object;    = = Cannot compare an object that does not have an inheritance relationship the default Equals method of the string class is considered equal as long as the character sequence of the object is equal;    The Equals method of the string class overrides the Equals method of the object class, which differs little from = =. In general, we require that the same value be the same as the String class @see java.lang.string#964*/     Public Booleanequals (Object obj) {//determine whether two objects are the same object       if( This==obj) {            return true; }        //When obj is not null and is an instance of Cacheperson        if(obj! =NULL&& Obj.getclass () = = Cacheperson.class) {Cacheperson ci=(Cacheperson) obj; returnname.equals (Ci.getname ()); }        return false; }     Public inthashcode () {returnName.hashcode (); }} Public classCachepersontest { Public Static voidMain (string[] args) {Cacheperson C1= cacheperson.valueof ("Hello"); Cacheperson C2= cacheperson.valueof ("Hello"); //output:trueSYSTEM.OUT.PRINTLN (C1 = =C2); }

Digression: To be honest, about Java in the case of a string, immutable class, can only understand 60%. I wrote it here for the time being. When the perception is high, look back.

Java Immutable classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.