This article summarizes the top 10 list of errors that Java developers often commit.
Top1. Array conversions to arrays list
Convert arrays to array lists, which developers often do:
[Java]View Plaincopy
- list<string> list = Arrays.aslist (arr);
Arrays.aslist () returns an array of ArrayList inside the private static class, which is not a java.util.ArrayList class, and the Java.util.Arrays.ArrayList class has set (), Get (), The contains () method, but does not have any method of adding elements, so its size is fixed. You should do this to create a real array:
[Java]View Plaincopy
- arraylist<string> ArrayList = new Arraylist<string> (Arrays.aslist (arr));
The ArrayList constructor can accept a collection type, which is also a super type of java.util.Arrays.ArrayList.
Top2. Check that an array contains a value
Developers often do this:
[Java]View Plaincopy
- set<string> set = new Hashset<string> (Arrays.aslist (arr));
- Return Set.contains (Targetvalue);
The code can work, but it is not necessary to first convert the list to set, and it takes extra time to convert a list to a set. So you can simplify it to:
[Java]View Plaincopy
- Arrays.aslist (arr). Contains (Targetvalue);
Or
[Java]View Plaincopy
- for (String S:arr) {
- if (s.equals (targetvalue))
- return true;
- }
- return false;
The first one is more readable than the second one.
Top3. Remove an element from a list in a loop
Consider the result of the code in the iteration that deletes the element below:
[Java]View Plaincopy
- 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:
[Java]View Plaincopy
- [B, D]
There is a serious problem with this approach, when an element is deleted, the size of the list shrinks and the pointer changes. So it's not normal to want to remove multiple elements within a loop using pointers.
Using iterators in this case is the right approach, and the Foreach Loop works in Java like an iterator, but it's not, in fact, consider the following code:
[Java]View Plaincopy
- arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
- for (String s:list) {
- if (s.equals ("a"))
- List.remove (s);
- }
It will report a concurrentmodificationexception exception.
On the contrary, this will work properly.
[Java]View Plaincopy
- 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 called before. Remove (). In the Foreach loop, the compiler calls after the element operation is deleted. Next (), which is also the cause of the concurrentmodificationexception exception, you can click here to view the source code of Arraylist.iterator ().
Top4. Hashtable vs HashMap
According to the conventional algorithm, Hashtable is the name of the data structure. In Java, however, the name of the data structure is hashmap. One of the key differences between Hashtable and HashMap is that Hashtable is synchronous.
For this, you can see the following two links:
HashMap vs. TreeMap vs. Hashtable vs. Linkedhashmap
Map Problem Top10
Top5. Use the original type of the collection
In Java, primitive types and unrestricted wildcard types are easily confused. In set, for example, set is the original type, and set (?) is an unrestricted wildcard type.
Consider the following code, with an original type list as the parameter:
[Java]View Plaincopy
- Public static void Add (List list, Object o) {
- List.add (o);
- }
- Public static void Main (string[] args) {
- list<string> list = new arraylist<string> ();
- Add (list, 10);
- String s = list.get (0);
- }
The code throws an exception:
[Java]View Plaincopy
- Exception in thread "main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String
- At ...
Using the collection of primitive types is dangerous because the collection of primitive types skips the generic type check and is not secure. There is a big difference between Set, set<?>, and set<object>. More detail to view
Raw type vs. unbounded wildcard and type Erasure.
Top6. Access level
Developers often use public for class domains, which makes it easy to get domain values by direct reference, but this is a very bad design. By experience, the lower the level of access that is given to members, the better.
For details, click to view member access levels in Java: Public, protected, private
Top7.arraylist VS LinkedList
If you don't know the difference between ArrayList and LinkedList, you may often choose ArrayList because it looks familiar. However, there is a huge difference in performance between them. Simply put, LinkedList should be your first choice if you have a large number of Add/delete operations and do not have a lot of random access operations. If you don't know much about this, click here to see more information about their performance.
TOP8. Mutable VS Immutable
Immutable objects have many advantages, such as simplicity, security, and so on. But it requires each different value to have a different object, and too many objects can lead to a high cost of garbage collection. So the choice of mutable and immutable should have a balance point.
In general, the Mutable object is used to avoid producing too many intermediate objects, and the classic example is the number of strings connected. If you use the immutable string, you will have many objects that meet the garbage collection criteria. This is a waste of time and effort on the CPU when it can use the Mutable object as the correct solution. (e.g. StringBuilder)
[Java]View Plaincopy
- String result="";
- for (String S:arr) {
- Result = result + S;
- }
There are also some other scenarios where mutable objects are desirable. For example, a Mutable object passed into a method allows you to collect multiple results without skipping too many grammars. Another example is sorting and filtering, and you can build a method with the original collection and return a sorted one, but this is a bigger waste for large collections.
Recommended reading: Why is the string immutable?
TOP9. Super and Sub constructors
This compilation error is because the default super constructor is undefined. In Java, if a class does not have a constructor defined, the compiler defaults to inserting a parameterless constructor for the class. If a constructor is defined in the Super class, in which case super (String s), the compiler does not insert the default parameterless constructor.
The Sub class's constructor, on the other hand, calls the parameterless super constructor, regardless of the band without parameters.
The compiler attempted to insert super () into two constructors in the Sub class, but the super default constructor is undefined and the compiler will not error. How to solve this problem? You simply add a super () constructor to the Super class, as follows:
[Java]View Plaincopy
- Public Super () {
- System.out.println ("Super");
- }
Or remove the custom super constructor, or add super (value) in the Sub function.
For more information on this, you can click here to view.
Top10. "" or constructor?
Strings can be created in two ways:
[Java]View Plaincopy
- 1. Use double quotes
- String x = "abc";
- 2. Use constructor
- String y = new string ("abc");
What's the difference between them? The following example can give an answer:
[Java]View Plaincopy
- string a = "ABCD";
- string b = "ABCD";
- System.out.println (a == b); //&NBSP;TRUE&NBSP;&NBSP;
- System.out.println (a.equals (b)); //&NBSP;TRUE&NBSP;&NBSP;
- &NBSP;&NBSP;&NBSP;
- string c = new string (
- string d = new string (
- System.out.println (c == d); // false
- system.out.println (C.equals (d)); < span class= "comment" >// true
More details on how they are distributed in memory can be viewed using the or constructor to create a Java string.
Java developers are prone to make mistakes Top10