Are you a passing Java programmer (1)

Source: Internet
Author: User

After many years of writing Java programs, must they be a passing Java programmer? I dare not say that I am a qualified Java programmer. I barely pass.
Let's start with the most common string in the project.
1. About replace and replaceall
Many brothers know that replace is replaced only once and replaceall is replaced all.
Replace is a regular string replacement, and replaceall is a regular expression replacement. It is strange that sun Engineers cannot name the two methods well. replaceall is much better if it is changed to replaceregex.
In addition, the first replaceall is a regular expression, and the second is to replace the string. The correct usage of this function is:
Use pattern. Quote () for the first parameter ()
Use matcher. quotereplacement () for the second parameter ()
Reference: Java puzzlers puzzle 20: What's my class? Puzzle 21: What's my class, take 2
2. About split
In actual projects, you will often use a combination of several parameters with a special character, and then split them with a split, for example:
String Params = "AA | BB | CC | dd ";
String paramarray [] = Params. Split ("| ");
It seems correct. In fact, people use regular expressions to split, and | it has special significance in the regular expression, so this is a problem.
Since replace can have a twin brother replaceall, why can't split have twin sisters splitall or splitregex?
In addition, split can have the second parameter, split (RegEx, limit). What does this second parameter mean?
What do we say in our API documentation:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. if the limit N is greater than zero then the pattern will be applied at most n-1 times, the array's length will be no greater
Than N, and the array's last entry will be contain all input beyond the last matched delimiter. if n is non-positive then the pattern will be applied as usual times as possible and the array can have any length. if n is zero then the pattern will be applied
Lost times as possible, the array can have any length, and trailing empty strings will be discarded.
If limit is <0, it will be split as much as possible
If Limit = 0, the system splits the string as much as possible, but the null string at the end is lost.
If the limit value is greater than 0, a maximum of limit-1 splits are performed. The maximum length of the split string array is limit.
"AA, BB,". Split (","). Length = 2
"AA, BB,". Split (",", 0). Length = 2
"AA, BB,". Split (",",-1). Length = 7
3. I have met something like synchronized (string ).
This is not a good description. Let's look at the Code directly:
Class worker implements runnable {
Private int COUNT = 0;
@ Override
Public void run (){
String lock = "mylock ";
Synchronized (LOCK ){
Try {thread. Sleep (100);} catch (exception e) {e. printstacktrace ();}
Count ++;
System. Out. println (thread. currentthread (). getname () + "count:" + count );
Count --;
System. Out. println (thread. currentthread (). getname () + "count:" + count );
}
}
}
Public class test1 {
Public static void main (string [] ARGs ){
Worker = new worker ();
For (INT I = 0; I <10; I ++ ){
Thread t = new thread (worker );
T. Start ();
}
}
}
At first glance, the lock object is the internal variable of the method, so it does not play the role of synchronization at all, but what is actually? After running the code, we can see that people are indeed synchronized!
Because the literal constant of string only retains one copy in the constant pool of a virtual machine, even the internal variable actually has only one copy, so it can be used as a lock,
Of course, this is not necessarily the case if we can do this. I didn't see the reason why we had to do this. To invalidate the above lock, it is also simple: string lock = new string ("mylock"); in this case,
Every time it is a new object, it is definitely not the same lock, and it will not be synchronized!
Below is the bytecode:
(1) When string lock = "mylock ";
Stack = 3, locals = 5, args_size = 1
0: LDC #3 // string mylock
2: astore_1
3: aload_1
4: DUP
5: astore_2
6: monitorenter
(2) string lock = new string ("mylock ");
Stack = 3, locals = 5, args_size = 1
0: New #3 // class Java/lang/string
3: DUP
4: LDC #4 // string mylock
6: invokespecial #5 // method Java/lang/string. "<init>" :( ljava/lang/string;) V
9: astore_1
10: aload_1
11: DUP
12: astore_2
13: monitorenter
For more information, see Java language specification, 3.10.5 string literals.
We do not recommend using string objects as locks. If you do not need to use them, you can use synchronized (Str. Intern ()).
4. Let's look at a question about set initialization:
All the collection classes in Java basically have a constructor with a specified set size, such as arraylist. If we know exactly that the number of list elements is N, when we define a list, you can do this:
List <string> List = new arraylist <string> (n); this does not mean that the List constructed by this constructor can only contain n elements, but it only indicates that during initialization, you can add n elements. When the elements cannot be installed, they will be resized.
The advantage of specifying the initial capacity is obvious, because the default arraylist has 10 elements. If our list has fewer elements and only five elements, we can save half of the space, if there are more than 1000 elements,
If the initialization size is not specified, it takes 12 Resizing in the middle to put the 1000 elements int newcapacity = oldcapacity + (oldcapacity> 1); hashmap is a little special, because it also has a concept of load factor, that is to say, hashmap will not wait until all the buckets are filled up before resizing. Instead, it will reach a certain proportion and start resizing. The default value is 0.75, because hashmap expansion requires re-calculation of hashcode for all the elements in it, if the number of elements is large, it is relatively time-consuming. If yes, we try to reduce the number of resizing times.
The following is a Class I wrote to calculate the hashmap initialization capacity:
Public class hashmaputil {
/**
* Calculate the capacity of the hashmap required for storing realcount elements to avoid resizing.
*
* @ Param realcount refers to the number of elements to be stored.
**/
Public static int capacity (INT realcount ){
Return capacity (realcount, 0.75 );
}
/**
* Calculate the capacity of the hashmap required for storing realcount elements to avoid resizing.
*
* @ Param realcount refers to the number of elements to be stored.
* @ Param loadbalance load factor
**/
Public static int capacity (INT realcount, double loadbalance ){
If (realcount <= 1 ){
Return 1;
}
Int capacity = 1;
While (capacity * loadbalance <realcount ){
Capacity = capacity <1;
}
Return capacity;
}
}
Similar to stringbuffer and stringbuilder, if the size is specified during the construction, the number of resizing times can be reduced and the efficiency can be improved.

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.