Java developers are prone to make mistakes Top10

Source: Internet
Author: User
Tags concurrentmodificationexception

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
    1. 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
    1. 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
    1. set<string> set = new Hashset<string> (Arrays.aslist (arr));
    2. 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
    1. Arrays.aslist (arr). Contains (Targetvalue);

Or

[Java]View Plaincopy
    1. for (String S:arr) {
    2. if (s.equals (targetvalue))
    3. return true;
    4. }
    5. 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
    1. arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
    2. for (int i = 0; i < list.size (); i++) {
    3. List.remove (i);
    4. }
    5. SYSTEM.OUT.PRINTLN (list);

The output is:

[Java]View Plaincopy
    1. [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
    1. arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
    2. for (String s:list) {
    3. if (s.equals ("a"))
    4. List.remove (s);
    5. }

It will report a concurrentmodificationexception exception.

On the contrary, this will work properly.

[Java]View Plaincopy
    1. arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D"));
    2. Iterator<string> iter = List.iterator ();
    3. while (Iter.hasnext ()) {
    4. String s = iter.next ();
    5. if (s.equals ("a")) {
    6. Iter.remove ();
    7. }
    8. }

. 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
    1. Public static void Add (List list, Object o) {
    2. List.add (o);
    3. }
    4. Public static void Main (string[] args) {
    5. list<string> list = new arraylist<string> ();
    6. Add (list, 10);
    7. String s = list.get (0);
    8. }

The code throws an exception:

[Java]View Plaincopy
    1. Exception in thread "main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String
    2. 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
    1. String result="";
    2. for (String S:arr) {
    3. Result = result + S;
    4. }

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
    1. Public Super () {
    2. System.out.println ("Super");
    3. }

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. 1. Use double quotes
    2. String x = "abc";
    3. 2. Use constructor
    4. String y = new string ("abc");

What's the difference between them? The following example can give an answer:

[Java]View Plaincopy
    1. string a =  "ABCD";  
    2. string b =  "ABCD";   
    3. System.out.println (a == b);   //&NBSP;TRUE&NBSP;&NBSP;
    4. System.out.println (a.equals (b));  //&NBSP;TRUE&NBSP;&NBSP;
    5. &NBSP;&NBSP;&NBSP;
    6. string c = new string (
    7. string d = new string (
    8. System.out.println (c == d);   // false  
    9. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.