Java invariant string

Source: Internet
Author: User
Tags contains garbage collection integer stringbuffer

Please observe the following code:

: Stringer.java public

class Stringer {
  static String upcase (String s) {return
    s.touppercase ();
  }
  public static void Main (string[] args) {
    String q = new String ("Howdy");
    SYSTEM.OUT.PRINTLN (q); Howdy
    String qq = upcase (q);
    SYSTEM.OUT.PRINTLN (QQ); HOWDY
    System.out.println (q);//HOWDY
  }
}///:~

When Q passes into UpCase (), it is actually a copy of the handle to Q. The object to which the handle is connected is actually located at a single unified physical location. When a handle is passed around, its handle is copied.
If you look at the definition of upcase (), you will find that the handle to the pass has a name s, and that name only exists during upcase () execution. When UpCase () is finished, the local handle s disappears and upcase () returns the result-or the original string, except that all characters are capitalized. Of course, what it returns is actually a handle to the result. But the handle returned is ultimately a new object, while the original q has not changed. How did all of this happen?

1. Implicit constants
If you use the following statement:
String s = "asdf";
String x = stringer.upcase (s);
So do you really want the UpCase () method to change the arguments or parameters? We are usually unwilling, because as a kind of information provided to the method, the independent variables are usually presented to the reader of the code, rather than let them modify it. This is a fairly important guarantee because it makes code easier to write and understand.
To implement this assurance in C + +, you need help with a special keyword: const. With this keyword, the programmer can guarantee that a handle (C + + called "pointer" or "reference") will not be used to modify the original object. But in this way, C + + programmers need to remember to use const everywhere. This is clearly confusing and not easy to remember.

2. Cover "+" and StringBuffer
Using the techniques mentioned earlier, the objects of the string class are designed to be "immutable." If you look at the contents of the string class in the online documentation (which is summarized later in this chapter), you will find that each method in the class that can modify a string actually creates and returns a new string object that contains the modified information-the original string is intact. Therefore, there is no feature in Java that corresponds to the const of C + + to allow the compiler to support the immutable capabilities of the object. If you want to acquire this ability, you can set it yourself, just like a string.
Because a string object is immutable, it is possible to perform multiple aliases on a particular string, depending on the situation. Because it is read-only, it is not possible for a handle to change something that affects other handles. Therefore, a read-only object can be a good solution to the alias problem.
By modifying a new version of the resulting object, it seems that you can resolve all problems with modifying objects, just like string. But for some operations, this method is not efficient. A typical example is the operator "+" that overrides a string object. "Overwrite" means that when used with a particular class, its meaning has changed (for string "+" and "+ +" are the only operators in Java that can be overridden, and Java does not allow programmers to overwrite any other operator--comment ④).

④:c++ allows programmers to override operators arbitrarily. Since this is usually a complex process (see "Thinking in C + +", Prentice-hall published in 1995), the Java designer has decided that it is a "bad" feature and decides not to use it in Java. Ironically, however, an operator's overlay is much easier in Java than in C + +.

When used against a string object, "+" allows us to concatenate different strings:

String s = "abc" + foo + "def" + integer.tostring (47);

You can imagine how it might work: the string "ABC" can have a method append (), which creates a new string that contains the contents of "ABC" and foo; this new string then creates another new string, adds "Def" to it, and so on.
This is a good idea, but it requires the creation of a large number of string objects. Although the ultimate goal is to get a new string containing all the content, a large number of string objects are used in the middle, and garbage collection is ongoing. I wonder if Java designers have tried a way first (this is a lesson of software development – it's impossible to really understand the system unless you try the code and get something running. I also wonder if they have long found that the performance of doing so is unacceptable.
The solution is to make a variable gay class like the one described earlier. For strings, this gay class is called StringBuffer, and the compiler can automatically create a stringbuffer to compute a particular expression, especially when a string object is applied to an overridden operator + and + =. The following example solves this problem:

: Immutablestrings.java
//Demonstrating StringBuffer public

class Immutablestrings {public
  static void Main (string[] args) {
    String foo = ' foo ';
    String s = "abc" + foo +
      "def" + integer.tostring (a);
    System.out.println (s);
    The "equivalent" using StringBuffer:
    stringbuffer sb = 
      new StringBuffer ("abc");//creates string!
    Sb.append (foo);
    Sb.append ("Def"); Creates string!
    Sb.append (integer.tostring);
    System.out.println (SB);
  }
///:~

When you create a string s, the compiler does the work roughly equivalent to the following code that uses SB--creating a stringbuffer and adding the new character directly to the StringBuffer object (instead of generating the new object each time) with append (). Although this is more efficient, it is not worth creating a quote string such as "abc" and "Def" each time, and the compiler converts them to string objects. So while StringBuffer provides greater efficiency, it produces more objects than we would expect.

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.