Bad code:
Public class WrongCompare {
/**
* @ Param args the command line arguments
*/
Public static void main (String [] args ){
String [] str1 = {"1", "2", "3", "4", "5", "6 ",};
String [] str2 = {"0", "2", "3", "4", "5", "6", "7 ",};
For (int I = 0; I <str1.length; I ++ ){
Boolean has = false;
For (int j = 0; j <str2.length; j ++ ){
If (str1 [I]. equals (str2 [j]) {
Has = true;
Break;
}
}
If (! Has ){
System. out. println (str1 [I] + "in str1, not in str2 ");
}
}
For (int j = 0; j <str2.length; j ++ ){
Boolean has = false;
For (int I = 0; I <str1.length; I ++ ){
If (str1 [I]. equals (str2 [j]) {
Has = true;
Break;
}
}
If (! Has ){
System. out. println (str2 [j] + "in str2, not in str1 ");
}
}
}
}
Comparing the differences between the two arrays, we used two double-layer loops for judgment. This overhead is very large.
Sometimes, we will find that the program we write is no problem during debugging, and once it is in the real environment, it will be too slow to stand.
Pay attention to skills when writing code.
Available Methods:
Public class RightCompare {
/**
* @ Param args the command line arguments
*/
Public static void main (String [] args ){
String [] str1 = {"1", "2", "3", "4", "5", "6 ",};
String [] str2 = {"0", "2", "3", "4", "5", "6", "7 ",};
Set set1 = new HashSet ();
Set set2 = new HashSet ();
Set1.addAll (Arrays. asList (str1 ));
Set2.addAll (Arrays. asList (str2 ));
Iterator iter = set1.iterator ();
While (iter. hasNext ()){
Object o = iter. next ();
If (set2.contains (o )){
Set2.remove (o );
} Else {
System. out. println (o + "in str1, not in str2 ");
}
}
Iter = set2.iterator ();
While (iter. hasNext ()){
Object o = iter. next ();
System. out. println (o + "in str2, not in str1 ");
}
}
}
Use the Set method. Set does not store data in a list. unordered data is more efficient.
Hashset uses a Hash hash algorithm to store data and determine whether the data is in the set. The overhead is much faster than that in the list, especially for large datasets.
This improvement in efficiency will be more obvious during mobile phone development.
From: http://blog.cs dn.net/yihui823/article/details/6912428