1. Convert an array to a list
When you convert an array to a list, programmers often do this:
1 |
List<String> list = Arrays.asList(arr); |
Arrays.asList()
Returns a ArrayList object, the ArrayList class is a private static class of Arrays, not a java.util.ArrayList class, and the Java.util.Arrays.ArrayList class has set (), Get (), Contains () method, but there is no way to add an element, so its size is fixed and you want to create a real ArrayList class, you should do this:
1 |
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr)); |
ArrayList's construction method can accept a collection type, just as it is also a java.util.Arrays.ArrayList superclass.
2. Determine if an array contains a value
Programmers often do this:
12 |
Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue); |
This code works, but there's no need to convert an array into a list, which takes extra time to convert to a list. It can be as simple as the following:
1 |
Arrays.asList(arr).contains(targetValue); |
Or is:
123456 |
for (String s:arr){ if (s.equals(targetValue)){ return true ; } } return false ; |
The first method is easier to read than the second.
3. Delete an element from a list in a loop
Consider the following section of code that deletes multiple elements in a loop
12345 |
ArrayList<String> list = new ArrayList<String>(Arrays.asList( "a" , "b" , "c" , "d" )); for ( int i= 0 ;i<list.size();i++){ list.remove(i); } System.out.println(list); |
The output is:
There is a serious error in this method. When an element is deleted, the size of the list shrinks and the subscript changes, so when you want to delete multiple elements in a loop with subscripts, it does not take effect normally.
You might know that the correct way to delete multiple elements in a loop is to use iterations, and you know that the Foreach loop in Java looks like an iterator, but it's not. Consider the following code:
123456 |
ArrayList<String> list =
new ArrayList<String>(Arrays.asList(
"a"
,
"b"
,
"c"
,
"d"
));
for
(String s:list){
if
(s.equals(
"a"
)){
list.remove(s);
}
}
|
It throws a concurrentmodificationexception exception.
Instead, the following display is normal:
12345678 |
ArrayList<String> list =
new ArrayList<String>(Arrays.asList(
"a"
,
"b"
,
"c"
,
"d"
));
Iterator<String> iter = list.iterator();
while
(iter.hasNext()){
String s = iter.next();
if
(s.equals(
"a"
)){
iter.remove();
}
}
|
.next()
Must be .remove()
called before. In a foreach loop, the compiler causes. Next () to be called after the element is deleted, so the concurrentmodificationexception exception is thrown, and you might want to look at the source code of Arraylist.iterator ().
Comparison of 4.Hashtable and HashMap
In terms of algorithms, a hash table is a name for a data structure. But in Java, the name of this data structure is hashmap. An important difference between Hashtable and HashMap is that the Hashtable is synchronous. So you often don't need hashtable, but hashmap often use it.
HashMap vs. TreeMap vs. Hashtable vs. Linkedhashmap
Top Ten questions about Map
5. Using the original type in the collection
In Java, primitive types and unbounded wildcard types can easily be mixed together, and set is a primitive type and a Set<?>
wildcard type without bounds.
Consider the following code that uses the original type list as a parameter:
1234567 |
public static void add(List list,Object o){
list.add(o);
}
pulbic
static void main(String[] args){
List<String> list =
new ArrayList<String>();
add(list,
10
);
String s = list.get(
0
);
|
This piece of code throws an exception:
12 |
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at ... |
It is dangerous to use a collection of native types, because the native type collection skips the generic type check and is not secure, Set
Set<?>
and is very different in, and set <Object>
, see Raw Type vs. unbounded wildcard and type Erasure.
6. Access level
Programmers often use public as a modifier for a class field, and can easily get a value by reference, but this is a bad design, and by experience, the level of access assigned to member variables should be as low as possible.
Public, default, protected, and private
Comparison of 7.ArrayList and LinkedList
When the handlers don't know the difference between ArrayList and LinkedList, they often use ArrayList, because it looks more familiar. However, they previously had huge performance differences. In short, if you have a large number of operations that increase the deletion and do not have a lot of random access elements, you should first LinkedList. If you've just touched them, check out ArrayList vs. LinkedList For more information on their performance.
8. Variable and non-changeable
Immutable objects have many advantages, such as simplicity, security, and so on. But for each of the different values requires a separate object, too many objects can cause a lot of garbage collection. There should be a balance when the choice is mutable and immutable.
In general, mutable objects are used to avoid generating a large number of intermediate objects. A typical example is the connection of a large number of strings. If you use an immutable string, you will have many objects that need to be garbage collected. This is a waste of CPU time, and using mutable objects is the correct solution (such as StringBuilder).
1234 |
String result= "" ; for (String s: arr){ result = result + s; } |
Sometimes you need mutable objects in some cases, such as passing mutable objects as arguments, and you can get multiple results without using many statements. Another example is sorting and filtering: Of course, you can write a method to receive the original collection and return an ordered set, but that would be too wasteful for large collections. (The answer from StackOverflow's Dasblinkenlight ' s)
Why String is immutable?
9. Constructors for parent and child classes
This compile-time error occurs when the default constructor method of the parent class is undefined, and in Java, if a class does not have a constructor defined, the compiler defaults to adding a parameterless constructor to the class. If a construction method is defined in the parent class, in this case super (String s), the compiler does not add the default parameterless constructor, which is the case of the parent class above.
The constructor of a subclass, whether it is a parameterless or a parameter, invokes the parameterless constructor of the parent class. Because the compiler attempted to add the super () method to the two constructor methods of a subclass. However, the default constructor method of the parent class is undefined, and the compiler will report the error message.
To fix this problem, you can simply add a super () constructor to the parent class by 1), like this:
123 |
public Super(){ System.out.println( "Super" ); } |
or 2) Remove the parent class custom constructor method, or 3) call the super (value) method of the parent class in the constructor method of the child class.
Constructor of Super and Stub
10. "" or the constructor
There are two ways to create a string
1234 |
//1.使用字符串 String x = "abc" ; //2.使用构造器 String y = new String( "abc" ); |
What's the difference?
The following example gives a quick answer:
123456789 |
String a =
"abc"
;
String b =
"abc"
;
System.out.println(a==b);
//true
System.out.println(a.equals(b));
//true
String c =
new String(
"abc"
);
String d =
new String(
"abc"
);
System.out.println(c==d);
//false
System.out.println(c.equals(d));
//true
|
(RPM) The 10 most common mistakes that Java programmers make