In the coding process, arrays are one of the most commonly used data structures. However, arrays are the data structures we are most likely to discard. They are often replaced by arraylist and other collection classes due to initialization and Fixed Array length. In fact, arrays are the simplest set of data. Compared with other set data, arrays have the advantages of simple operations and fast query speed. Vulnerabilities with fixed length can also be solved in many cases. In addition, in the coding process, some of them are intuitive so that we can use arrays, but in many cases they are not so intuitive. We need to analyze them a little. The summary in this article is to explain some aspects of array usage that are ignored and can display the advantages of array. It is hoped to be used as an example to help you mine the array usage.
First, array to if... Else... And case statement Improvement
In our coding process, if statements can be seen everywhere. Code During review, we often see some very long if... Else if... Such a statement is very dazzling, But it seems helpless.
Boolean flag = true;
Switch (operatorid)
{
Case 1:
Conditionsql + = ">" + "'" + cond + "'";
Break;
Case 2:
Conditionsql + = "> =" + "'" + cond + "'";
Break;
Case 3:
Conditionsql + = "<" + "'" + cond + "'";
Break;
Case 4:
Conditionsql + = "<=" + "'" + cond + "'";
Break;
Case 5:
Conditionsql + = "=" + "'" + cond + "'";
Break;
Case 6:
Conditionsql + = "like" + "'%" + cond + "% '";
Break;
Default:
Flag = false;
Break;
}
This is the code of a case statement I copied. During the code review process, I also found a lot longer than this code, therefore, such code is representative.
Let's look at this statement: conditionsql + = ">" + "'" + cond + "'"; it is obviously a repetitive statement. The difference between each such statement lies in the preceding ">", "> =", "<", "<=", "=", and so on. Their corresponding conditions are 1, 2, 3, 4, and so on. We can see from our observation that if the result is an array item, the condition is the subscript of the array. Look, it's perfect.
Therefore, modify the preceding statement as follows:
String [] conditionsqls = new string [] {"> '", "> ='", "<'", "<='", "= '", "Like '% "};
Boolean flag = true;
If (operatorid> = 1 & operatorid <= 6)
{
Conditionsql + = conditionsqls [operatorId-1] + cond + "'";
}
Else flag = false;
Is this much more concise?
Second, array improvement on a large number of repetitive statements
During the encoding process, we often have such repetitive statements:
Request. setattribute ("getuserlist", list );
Request. setattribute ("itemlist", list );
Request. setattribute ("tag1", tag );
Request. setattribute ("regulartotal", regulartotal );
Request. setattribute ("probationtotal", probationtotal );
Request. setattribute ("emptotal", emptotal );
Request. setattribute ("deptemplist", deptemplist );
We have also encountered such a value assignment statement:
String contractid = request. getparameter ("contractid ");
String categoryid = request. getparameter ("categoryid ");
String employeeid = request. getparameter ("employeeid ");
String contractnumber = request. getparameter ("contractnumber ");
String content = request. getparameter ("content ");
String validitydate = request. getparameter ("validitydate ");
String contractterm = request. getparameter ("contractterm ");
String probationtime = request. getparameter ("probationtime ");
String pay = request. getparameter ("pay ");
String probationpay = request. getparameter ("probationpay ");
String createdate = request. getparameter ("createdate ");
Obviously, such statements can be simplified using arrays. Let's first look at the first statement, we can see at a glance, request. setattribute ("getuserlist", list); duplicate. The difference between each statement is that the first parameter of setattribute is different from the second parameter. The solution is obviously to make an array of both a parameter and the second parameter:
String [] names = new string [] {"getuserlist", "itemlist", "tag1", "regulartotal", "probationtotal", "emptotal", "deptemplist "};
Object [] values = new object [] {list, list, Tag, regulartotal, probationtotal, emptotal, deptemplist };
For (INT I = 0; I <names. length; I ++)
{
Request. setattribute (name [I], values [I]);
}
For the second statement, why should we define so many variables? Instead of using an array?
Third, duplicate judgment statements that are irrelevant to each other
We have also encountered a large number of repeated single-condition judgment statements, such as the following example:
If (objectutils. isnullorempty (categoryid ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. categoryid "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (employeeid ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. employeeid "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (contractnumber ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. contractnumber "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (validitydate ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. validitydate "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (contractterm ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. contractterm "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (probationtime ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. probationtime "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (Pay ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. Pay "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (probationpay ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. probationpay "));
Saveerrors (request, errors );
}
If (objectutils. isnullorempty (createdate ))
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add. createdate "));
Saveerrors (request, errors );
}
}
This If statement does not have an else, and every one has to judge that it is actually a loop statement. The modified code is as follows:
String [] values = newstring [] {categoryid, employeeid, contractnumber, validitydate, contractterm, probationtime, pay, probationpay, createdate };
String [] infonames = new string [] {"categoryid", "employeeid", "contractnumber", "validitydate", "contractterm", "probationtime", "pay ", "probationpay", "createdate "};
For (INT I = 0; I <values. length; I ++)
{
If (objectutils. isnullorempty (Values [I])
{
Errors. Add (actionerrors. global_error,
New actionerror ("contractinfo. Add." + infonames [I]);
Saveerrors (request, errors );
}
}
Fourth, use a zero-length array.
When using arrays, we often see the following statements:
If (names! = NULL)
{
For (INT I = 0; I <names. length; I ++)
{
......
}
}
Obviously, names is an array, but it is necessary to judge whether it is not empty. This If statement makes people feel a lot of this, but helpless.
As a matter of fact, when names is empty, the reason is that when the names array is assigned a value, there is a situation where names is not initialized, this is not allowed in our coding process.
The solution is to initialize a zero-length array when names is initialized. For example:
String [] names;
String condition = "1 ";
If (condition. Equals ("2 "))
{
Names = new string [] {"name1", "name2 "};
}
Else
{
Names = new string [] {};
}
For (INT I = 0; I <names. length; I ++)
{
System. Out. println (Names [I]);
}
Fifth, the array usage of the arrays library.
There are some good methods in the arrays library of Java APIs, which are listed below:
1. query the array: binarysearch
String [] strs1 = new string [] {"1", "2", "3", "4 "};
Int I = arrays. binarysearch (strs1, "2 ");
System. Out. println (I );
2. array overwrite: Fill
String [] strs1 = new string [] {"1", "2", "3", "4 "};
Arrays. Fill (strs1, 2, 3, "Haha ");
For (INT I = 0; I <strs1.length; I ++)
{
System. Out. println (strs1 [I]);
}
Note: The first parameter is an array, and the last parameter is the new value after overwriting. The overwrite position is. Starting from the second parameter, the number of overwrite array items is, the third parameter minus the second parameter.
3. Sorting of Arrays: Sort
String [] strs1 = new string [] {"1", "2", "6", "4 "};
Arrays. Sort (strs1 );
For (INT I = 0; I <strs1.length; I ++)
{
System. Out. println (strs1 [I]);
}
Sixth, data and other data types Conversion
We often need to convert the array to some data types such as list and arraylist, and then we need to convert them back.
Convert the array to list:
String [] strs1 = new string [] {"1", "2", "6", "4 "};
List list = arrays. aslist (strs1 );
Convert the array to arraylist:
String [] strs1 = new string [] {"1", "2", "6", "4 "};
List list = arrays. aslist (strs1 );
Arraylist Al = new arraylist ();
Al. addall (list );
Convert list to array:
String [] strs1 = new string [] {"1", "2", "6", "4 "};
List list = arrays. aslist (strs1 );
String [] strs2 = (string []) List. toarray (New String [0]);
For (INT I = 0; I <strs2.length; I ++)
{
System. Out. println (strs1 [I]);
}
7. Remove the same items from the array.
We know that the items in the array can be repeated. Sometimes we need to remove the repeated items in the array. What should we do? We also know that there are no repeated items in the hashset. Can we convert the array into a hashset and then convert it back?
String [] strs1 = new string [] {"1", "2", "6", "4", "2", "4 "};
Hashset set = new hashset ();
Set. addall (arrays. aslist (strs1 ));
String [] strs2 = (string []) set. toarray (New String [0]);
For (INT I = 0; I <strs2.length; I ++)
{
System. Out. println (strs1 [I]);
}
Eighth, copying Arrays
We can copy some items of an array to another array, for example:
String [] strs1 = new string [] {"1", "2", "3", "4", "5", "6 "};
String [] strs2 = new string [4];
System. arraycopy (strs1, 2, strs2, 0, 2 );
For (INT I = 0; I <strs2.length; I ++)
{
System. Out. println (strs2 [I]);
}
The above code copies the strs1 array to the strs2 array. Copy the strs1 array from the entry whose subscript is 2 to the entry whose subscript is 0.
Ninth, an undefined Array
If the length of an array is limited, you can use the following method:
String [] array;
If (length. Equals ("4 "))
{
Array = new string [4];
......
}
Else if (length. Equals ("9 "))
{
Array = new string [9];
......
}
Else if (length. Equals ("10 "))
{
Array = new string [10];
......
}
Else array = new string [] {};
If not, you can use reflection to generate an array, for example:
Try {
Int length = 10;
Class CLS = Class. forname (
"Java. Lang. String ");
Object arr = array. newinstance (CLS, length );
String [] STRs = (string []) Arr;
For (INT I = 0; I <STRs. length; I ++)
{
STRs [I] = string. valueof (I );
}
For (INT I = 0; I <STRs. length; I ++)
{
System. Out. println (STRs [I]);
}
}
Catch (throwable e ){
System. Err. println (E );
}
Array advantages:
1. You do not need to perform transformations, because the arrays all belong to the same type. It is useful in some cases. Especially in the case of multi-dimensional arrays.
2. the array cannot be finite. It means that the array should not be used when continuing, but other data structures, such as list. We do not recommend using reflection to generate dynamic arrays (obviously C-thinking ). We recommend that you convert arrays. aslist to list. If you need to set the parameter to an array, You can first operate on the list, and then generate an Array Using arrays. toarray.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/nomily/archive/2009/06/12/4263286.aspx