java-in-depth-string,object, regular expressions

Source: Internet
Author: User

We've already covered the basics of Java and the simple OOP object-oriented programming idea. It means that you are already in the world of Java. But now you, as if a layman, just put his foot into this treasure trove, have not had time to find the treasure inside the treasure. But don't worry, success is always left to those who are prepared, and we're ready for you, so let's go into the treasure trove of Java and discover more interesting things. It's like the subject of our day:

String, StringBuffer, StringBuilder class

We have introduced the knowledge of string in the Java Foundation, but also confined to the superficial (basic stage), and now we will give you a layer of mask, let you have a deeper understanding of it. Words do not say much, wonderful start immediately!
First, let's take a look at what the String class is: its source code (part) is as follows:

 Public Final  class String implements Serializable, comparable<string  charsequence {...Private Final Char[] value;Private Final intOffsetPrivate Final int Count;.../** * Creates an empty string. */     PublicString () {value = Emptyarray.char; offset =0;Count=0; }/ * Private constructor used for JIT optimization. */@SuppressWarnings ("Unused")PrivateString (string S,Charc) {offset =0; Value =New Char[S.Count+1];Count= S.Count+1; System.arraycopy (S.value, S.offset, value,0, S.Count); Value[s.Count] = C; }....}

You see, we can find from the source code that the string class is modified by the final keyword, that is, the string is not inherited, what does it mean? We know that inheritance enables polymorphism and facilitates the reuse of code. But sometimes, there are some principled things, like a car's core original, we can not be arbitrarily to make changes. As a result of the change, perhaps the entire car will be scrapped. In the Java language, in order to ensure that the system can run correctly, engineers will be some system-level classes with final decoration, so as not to be arbitrarily modified by people to create some unnecessary trouble. In addition, the heart of the child will find that in the source code, the string object is actually a set of final modified char[], therefore, the string object is also known as a string constant, it cannot be modified again and cannot be inherited. This can testify to the Java Foundation string, which is written in this article, and the contents of string are described in this post. This is no longer the majority, we talk about the other two characters: Stringbuilderr and StringBuffer.
First Look at StringBuilder:

 Public Final  class StringBuilder extends abstractstringbuilder  implements  Appendable, charsequence, Serializable {        ······ Public StringBuilder() {    } Public StringBuilder(intcapacity) {Super(capacity); } Public StringBuilder(charsequence seq) {Super(Seq.tostring ()); } Public StringBuilder(String str) {Super(str); }    ······

We find that here, StringBuilder inherits a Abstractstringbuilder, and its construction method is eventually all implemented by the constructor of the parent class, so Let's take a look at how the parent class constructs a StringBuilder object:

AbstractClass Abstractstringbuilder {StaticFinalintInitial_capacity = -;Private Char[]value;Private intcount; Abstractstringbuilder () {value=New Char[Initial_capacity]; } abstractstringbuilder (intcapacity) {if(Capacity <0) {Throw NewNegativearraysizeexception (integer.tostring (capacity)); }value=New Char[Capacity]; } abstractstringbuilder (Stringstring) {count =string. Length (); Shared =false;value=New Char[Count + initial_capacity];string. _getchars (0, Count,value,0); }·····}

We look again and find that in this abstract parent class, value is no longer the final modified char[], that is, our StringBuilder can be modified. If string is a string constant, then it is a string variable. So, what about the StringBuffer? Let's look at its source code again:

public   Final  class   StringBuffer  extends  abstractstringbuilder  implements  appendable , serializable , charsequence  {}  

See here, we have found a problem, StringBuilder and StringBuffer are inherited from Abstractstringbuilder. In other words, the nature of the two is the same, all belong to the string variable. So what's the difference between them? In fact, there is, but it is not appropriate to say more, because it involves the content of the future, here first dig pits. Just know that StringBuilder is thread insecure, and StringBuffer is thread-safe. This knowledge point is one of the common questions, so need to master.
Next, we continue to say Stringbuider and StringBuffer. But because of the other operations of the two are consistent, is the line Shuo unsafe problem, so here directly selected StringBuffer for the following introduction, equivalent to StringBuilder.
The students who are impressed are aware that, as we said in the basic article, to change the length of a string, you can use a string connector to stitch strings and other data around them into a new string. This is because once the string object is established, the length cannot be changed. And now, StringBuffer as a variable exists, then it can change the length, naturally can also change the increase of the string ah. This is how to operate, in fact, the use is:

publicappend()

This method, through this method, can be implemented to StringBuffer object and character char/string/Another StringBuffer object/object together, without the need to create a stringbuffer to store. And this method is different from string, the other method and the string are consistent, this is also not introduced. Forget the children's shoes can go back to the basic blog post to see.

Object class

For the object class, this is a story-telling class. We know that the inheritance mechanism of Java is single-inheritance, that is, a class can inherit only one parent class, then the parent can inherit another parent class, so repeated, it is not caught in a dead loop? So, to avoid this cycle of death, we re-encapsulate the attributes of all classes into a new parent class, as the parent of all classes, and by default if a class does not inherit other parent classes, the class inherits directly from the parent class. Yes, he is the object class, the father of all classes. For this class, it is not recommended to look at the source code, because it involves a lot of JNI (Java Native Interface). This is for the current directory arrangement, is a super-section, in the future to introduce the JNI, and then this. What we need to know now is this kind of polymorphism application and some common methods:
First say polymorphism application, when we introduce polymorphism, we have already said that polymorphism refers to the various forms of objects, and the polymorphism of the class includes the transformation from the upward and the downward two kinds. At this level, all subclass types can be transformed upward to object, which makes it possible to avoid a lot of code redundancy when it comes to some kind of centralized operation. One example: in Android development, there is a class log that is used to print some kind of debug log. But it can only print a string type of data, so when we want to print other types of data, we need to type the conversion first. In order to centralize the process, we have done a bit of action:

//Set tool class for data printing  public  class  logutil{//static method, Available for external classes to call directly  //the first parameter is a label, which is used to flag the meaning of the printed data  // The second parameter is any type of information  public  static  void  showlog  (String Tag, ObJect obj);    The //log class is a class specific to Android that prints some kind of debug log     //i is a static method of the log class and is an abbreviation for info     //two parameters are required for string type  LOG.I (tag,string.valueof (obj));}  

You see, here we encapsulate the log class, call the Showlog method directly when we need to print it, and provide parameters, and the class will convert any type of argument we provide to a string type. In this, the object class is very successful, because it can represent all subclass types. This is where polymorphism is realized. Of course, this example is used in the development of Android, but also a more commonly used method, here is a simple introduction. Let us have a preliminary understanding. The main purpose is to understand the polymorphism of object.
OK, here are a few important ways to do this:
1.toString ()
This method is used to obtain a string representation of the specified object. What do you mean? That is, when we create an object, the object is present in the heap space, and the virtual machine generates a memory address that can be represented by a hashcode. But the problem is that we can't see the object, so is it? We can get it by this method, and its return is expressed as "type name @ memory address". For example:

Of course, this method can be overridden in a subclass, like the String class, which overrides the ToString method and returns the current object name. For example:

2.equals (Object obj)
about this method, is more important, it is also necessary to confuse. Its purpose is to compare whether the current object is the same object as the Obj object. What do you mean? As we have said above, the object is stored in the heap space, and a hachcode is used to indicate the memory address. That is, when we need to call this object, we need to take this memory address, it can be said that this memory address, is the object's unique identifier, if the hashcode is not equal, then it must be stated that the two objects are not equal. So is it that if the hashcode is equal, then the two objects must be equal? That's not necessarily the same. As for the reason, the third method will be explained at the time. Now, dig the pits first. Let's say first how to rewrite this equals method, there are five requirements:

1.自反性:对于任何非空引用x,x.equals(x)应该返回true。2.对称性:对于任何引用x和y,如果x.equals(y)返回true,那么y.equals(x)也应该返回true。3.传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,那么x.equals(z)也应该返回true。4.一致性:如果x和y引用的对象没有发生变化,那么反复调用x.equals(y)应该返回同样的结果。5.非空性:对于任意非空引用x,x.equals(null)应该返回false。

Here, let's do a resolution of the Equals method and the = = operator. Of course, take string as an example:
Let's take a look at how the equals has been modified in string:

 PublicBooleanequals(Object AnObject) {if( This= = AnObject) {return true; }if(AnObject instanceof String) {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; }

You see, in this case, the equals of string is not just a judgment of whether the two hashcode are equal. Instead of two hasncode, the content is judged to be equal, and if it is equal, returns True, or false. the = = operator only determines if the hashcode is equal, and if it is equal, true, unequal, false. Take a look at the example:
.
3.hashcode ()
This method returns the hashcode of the object in which the memory address is used as the hashcode default in object. So we're saying, if hashcode are equal, but the two objects are not necessarily equal, why is that? Because Hashcode is generated based on the hash algorithm, when we override this method, it is possible that the value returned may be the same because the algorithm chooses the reason. For example, we were going to return the variable i+1. But in the end, it was written in the last, which always returns the constant 2. Also, it is for this reason that we need to be clear: hashcode is not equivalent to memory address. The relationship between them is analogous to formal parameters and arguments. The memory address is immutable, but hashcode can change.

Regular expressions

About this knowledge point, it takes a long time to use to be handy, but it is very annoying, some people do not even know how to touch it, but it really improve the efficiency of development. The so-called regular expression is the string format matching rule. We can use it to monitor mailbox information, identity card information, mobile phone number information and so on whether these data is legal, generally used for data monitoring. So how does it match? Let's take a look at its matching definition.

正则表达式            匹配的字符串--------------      -------------------k                   kabc                 abc[abc]               a, b, c[abc][123]          a1,a2,a3,b1,b2,b3,c1,c2,c3[a-z]               a,z,k,r,h[a-zA-Z_0-9]        a,A,9,0,3,_[^a-zA-Z]           8,1,0,&,$,*\d                  数字\D                  排除数字\w                  单词字符[a-zA-Z_0-9]        \W                  排除单词字符\s                  空白字符\S                  排除空白字符.                   任意字符[\u4e00-\u9fa5]     中文范围[abc]?              ? 0或1个a,b,,c[abc]?[123]         a1, b2, 3[abc]*              * 0到多个[abc]+              + 1到多个                      a,b,c,aabbccabcabcabcbcabcccbcacbca[abc]{3}            aaa,abc,bbb,abc,cba,bac,ccc[abc]{3,5}          abc,abca,abcab[abc]{3,}           abc,abca,abcabccbacbccacbcaaa

With respect to regular expressions, it can be used in a variety of programming languages, with the following two classes in Java about it:

    * Pattern 封装一个正则表达式   * Matcher 封装正则表达式和要匹配的字符串

The object is created in the following way:
The first step: Pattern p = pattern.compile (regular expression);
Step two: Matcher m = P.matcher (string to match);
About this knowledge point, generally do not need to master more, but also must understand. We may not need to master the matching rules, but we need to learn how to monitor the legitimacy of the data. Here are a few methods of the Matcher class:

 【1】find()      向后查找下一段匹配的子串,返回字符串 【2】find(int from)    从 from 位置向后查找 【3】group()     取出刚刚找到的子串 【4】start()         取出刚刚找到的子串的起始位置 【5】end()          取出刚刚找到的子串的结束位置,end 位置不包含

Next, of course, is the correlation method for regular expressions

 【1】matches(正则表达式)          判断当前字符串,能否与正则表达式匹配 【2】replaceAll(正则表达式, 子串)          将找到的匹配子串,替换为新的子串  【3】split(正则表达式)      用匹配的子串,拆分字符串

In fact, originally introduced more Java class Library, but found that the first analysis of a class, rather than in a specific scene to analyze. Therefore, the introduction of the relevant class library, only a few of the more special classes. Interested students can take a look at the official Java documentation, to learn more about the point of knowledge. This is an advanced, but also a basis. Our next chapter is: java-in-depth-class set (core knowledge points), so stay tuned. If in doubt, please point out below, common improvement, thank you.

java-in-depth-string,object, regular expressions

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.