Err, who can have no. It is said that the Java language is a simple programming language, based on C + + evolution, eliminating many of the complex features of C + +, but this does not guarantee that Java programmers do not make mistakes. So what are the 10 most common mistakes that a Java programmer can make? This article summarizes the 10 most common mistakes that Java programmers make, which can effectively help the group of Java to take fewer detours, work less overtime, and write more robust applications.
1. Array turn ArrayList
In order to convert an array into a ArrayList, many Java programmers use the following code:
List<String> list = Arrays.asList(arr);
Arrays.aslist does return a ArrayList object, but the class is a private static inner class in the Arrays class, not a common java.util.ArrayList class. This java.util.Arrays.ArrayList class has a method such as set (), Get (), contains (), but does not have any methods to add or remove elements. Because the size of the class (size) is fixed. In order to create a real java.util.ArrayList, the code should look like this:
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));
We know that ArrayList's construction method can accept an object of type Collection, and our java.util.Arrays.ArrayList is just one of its subclasses. In fact, the more efficient code examples are:
ArrayList<String> arrayList = new ArrayList<String>(arr.length);Collections.addAll(arrayList, arr);
2. Whether the array contains a specific value
To check whether an array contains a specific value, many Java programmers use the following code:
Set<String> set = new HashSet<String>(Arrays.asList(arr));return set.contains(targetValue);
As far as functionality is concerned, the code is correct, but it consumes a lot of performance in the process of list,list and re-set the array. We can optimize it in the following form:
Arrays.asList(arr).contains(targetValue);
Or, further refine to the most efficient code shown below:
for(String s: arr){ if(s.equals(targetValue)) return true;}return false;
3. Remove elements from list at iteration
First, take a look at the code that removes the elements in the list during the iteration:
ArrayList<String>List=NewArrayList<String> (Arrays.Aslist(A, "B", "C","D")); For (int i = 0; I < list. Size(); I+ +) { list. Remove(i); System. Out. println(list);
The output from this sample code is:
[b, d]
There is a very serious error in this sample code. When an element is removed, the size of the list is reduced and the index is also changed to point to. Therefore, by using the index during the iteration, you will not be able to correctly delete multiple specified elements from the list.
You may know that one of the ways to resolve this error is to use an iterator (iterator). Also, you might think that a foreach statement in Java is very similar to an iterator (iterator), but that's not the case. Let's consider the following example code:
ArrayList<String>List=NewArrayList<string> (arrays. Aslist ( "a" "B" "C" , "D" (string s : list ) {if (s.equals ( "a" list.< Span class= "NA" >remove (s}
This example code will throw out a concurrentmodificationexception. We should modify it as follows:
ArrayList<String>List=NewArrayList<String> (Arrays.Aslist(A,"B",C,"D"));Iterator<string> iter = list iterator (); (iter. Hasnext ()) {string s = iter. (); if (s. Equals ( "a" {iter remove (); } /span>
The next () method must be called before the Remove () method. In the Foreach loop, the compiler causes the Remove () method to be called before the next () method, which results in a concurrentmodificationexception exception. Detailed details can be seen in the source code of Arraylist.iterator ().
4. Hashtable vs HashMap
Readers who have studied data structures know that a very important data structure is called a hash table. In Java, the class that corresponds to the hash table is HashMap instead of Hashtable. The core difference between HashMap and Hashtable is that HashMap is not synchronous and Hashtable is synchronous.
5. Using the original type in collection
In Java, it is easy to confuse primitive types with infinite wildcard types. Let's take a set-related example: Set is the primitive type;set<?> is the infinite wildcard type. Let's look at an example that uses the original type in the list:
PublicStaticvoidAdd(ListList,ObjectO){List.Add(O);}public static void main (string[] args) {List< Span class= "o" ><string> list = new arraylist<string> (); span class= "n" >add (list10string s = list. Get0
This example code throws an exception:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integercannot be cast to java.lang.String at ...
Using the original type in collection is a risk of a lot of type errors because the original type does not have a static type check. In fact, there is a very big difference between set, set<?>, and set.
6. Access rights
Many Java beginners prefer to use public to modify the members of a class. This makes it easy to access and access the member directly. However, this is a very bad programming style, and the right design style should be to minimize the access rights of class members.
7. ArrayList vs LinkedList
Many Java beginners do not understand the difference between ArrayList and LinkedList, so they simply use relatively simple ArrayList, and do not even know that there is linkedlist in the JDK. However, in some specific scenarios, the choice of these two lists can lead to significant differences in program performance. Simply put: When there are a lot of add/remove operations in the scenario, there are only a few random access operations, you should choose LinkedList; in other scenarios, consider using ArrayList.
8. Variable vs non-volatile
Immutable objects have many advantages, such as simplicity, security, and so on. However, for each of the different values, an object of the class is required. Also, the problem with generating many objects is that it can lead to frequent garbage collection. Therefore, when choosing a variable class or an immutable class, you should make a decision after considering it synthetically.
In general, mutable objects can avoid creating a large number of intermediate objects. A very classic example is the link to a large number of short string objects as a long string object. If you use the immutable string class, the linking process produces a large number of intermediate string objects that are suitable for immediate garbage collection, which consumes a lot of CPU performance and memory space. At this point, the use of a variable StringBuilder or stringbuffer is correct.
String result="";for(String s: arr){ result = result + s;}
In addition to the above, mutable objects may be due to immutable objects in other scenarios. For example, passing a mutable object to the inside of a method allows the object to collect multiple results without jumping in and out of multiple loop levels.
9. Constructors in inheritance
The two compile-time errors that occur in the parent class do not have a default constructor defined, and the default constructor for the parent class is called in the child class. In Java, if a class does not define any constructors, the compilation period automatically inserts a default constructor into the class. Once a class has defined any one constructor, the compilation period does not insert any constructors into the class. In the above example, the Super class defines a constructor that has a parameter type of string, so there is only one constructor in the class, and there is no default constructor.
&emps; in our subclass sub, we define two constructors: one constructor with the argument type string and the other a default function for lunch. Because none of them specifies which constructor of the parent class to call in the first line of the function body, they all need to call the parent class Super's default constructor. However, the default constructor for the parent Super is nonexistent, so the compiler reports both error messages.
10. Two ways to build a String object
A string object in Java has two common ways to create it:
//1. use double quotesString x = "abc";//2. use constructorString y = new String("abc");
What is the difference between them? Let's look at the following code:
StringA="ABCD";StringB="ABCD";System.Out.println(A==B);TrueSystem.Out.println(A.equals(B));TrueStringC=new string ( "ABCD" d = new string ( "ABCD" system.. (c == d); //falsesystem. Out. (c. Equals (d//True
10 errors commonly made by Java programmers