Top Mistakes Java developers make (GO)

Source: Internet
Author: User
Tags concurrentmodificationexception

The article lists some of the most common mistakes that Java developers make.

1. Converting an array to ArrayList

To convert an array to ArrayList, developers often do this:

?
1 List<String> list = Arrays.asList(arr);

arrays.aslist () returns a ArrayList, but this ArrayList is a private static class of Arrays , not Java.util.ArrayList. java.util.Arrays.ArrayList has a set (), get (), contains () method, but there is no way to add elements, So the size of it is OK. In order to create a real ArrayList, this should be done:

?
1 ArrayList<String> arrayList = newArrayList<String>(Arrays.asList(arr));

The ArrayList constructor can receive a Collection type, and it is also an ancestor class of java.util.Arrays.ArrayList .

2. Check if an array contains a value

Developers often do this:

?
12 Set<String> set = newHashSet<String>(Arrays.asList(arr));returnset.contains(targetValue);

This code can work, but it is not necessary to first convert the array to a collection, and it takes extra time to convert the array to a collection. You can do this:

?
1 Arrays.asList(arr).contains(targetValue);

Or

?
12345 for(String s: arr){    if(s.equals(targetValue))        returntrue;}returnfalse;

The first one is more readable than the second one.

3. Delete the elements of the list in the loop

Consider the following code, which deletes elements in a loop

?
12345 ArrayList<String> list = newArrayList<String>(Arrays.asList("a", "b", "c", "d"));for (inti = 0; i < list.size(); i++) {    list.remove(i);}System.out.println(list);

The output is as follows:

?
1 [b, d]

The above method has a serious problem. When an element is removed, the size of the list decreases and the index changes. Therefore, it is not available to use the index to delete multiple elements within a loop. You might know that using iterators to delete elements in a loop is the right approach, and that the foreach loop of Java is much like an iterator, but it's not. Consider the following code:

?
123456 arraylist<string> list = new arraylist<string> (Arrays.aslist ( "a" "B" "C" , Code class= "Java string" > "D"  for (String s:list) {     if (s.equals (         List.remove (s);

It will throw an exception concurrentmodificationexception. The following code is possible:

?
123456789 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();    }}

The . Next () method must be called before the . Remove () method is called. Inside the foreach loop, the compiler calls . Remove ()before calling . Next (), which causes the exception Concurrentmodificationexception. You may want to know the source code of Arraylist.iterator ().

4.HashTable vs HashMap

According to the algorithm's convention, Hashtable is the name of this data structure, but in Java, HashMap is the name of this data structure. One of the key differences between Hashtable and HashMap is that Hashtable is synchronous, and HashMap is not. So there is usually no need for more hashtable,hashmap. HashMap vs. TreeMap vs. Hashtable vs. Linkedhashmap Top 9 questions about Java Maps

5. Using the original collection type

In Java, primitive types and unbounded wildcard types are easily blended together. In set , for example,set is an original type, and set<? > is an unbounded wildcard type. Consider the following code that uses the original type List as a parameter:

?
12345678 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 above code will throw an exception:

?
1 Exception in thread "main"java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at ...

It is dangerous to use the original collection type because the original collection type skipped the generic type check and is not secure. There is a big difference between Set,set< > and set< Object > . Please refer to Raw type vs. unbounded wildcard and type Erasure.

6. Access level

Developers often use public as a modifier for a class, so it's easy to get a value by direct reference, but it's a very bad design. Based on experience, the level of access assigned to a member should be as low as possible. Public, default, protected, and private

7.ArrayList vs LinkedList

When developers don't know the difference between ArrayList and LinkedList, they usually use ArrayList because it looks more familiar. However, there is a big difference in performance between the two. Simply put, you should use LinkedList when there are a lot of insert/delete operations and there are not too many random access operations. If you are not familiar with this, refer to ArrayList vs. LinkedList.

8. Variable and non-changeable

Immutable objects have many advantages, such as simplicity, security, and so on. However, for each of the different values to have a separate object, too many objects cause the high consumption of garbage collection. There should be a tradeoff when choosing mutable and immutable. In general, mutable objects can be used to avoid producing too many intermediate objects. A classic example is the connection of a large number of strings, and the use of immutable strings will result in a large number of objects that need to be garbage collected. This wastes a lot of CPU time, and using mutable objects is the right solution (like StringBuilder).

?
1234 String result="";for(String s: arr){    result = result + s;}

In other cases, it is also necessary to use mutable objects, such as passing mutable objects as parameters, so that you can get multiple results without having to use 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). Why String is immutable?

9. Constructors for parent and child classes

Because there is no default constructor defined for the parent class, errors are generated at compile time. Inside Java, if a class does not have a constructor defined, the compiler inserts a default constructor with no parameters. If a constructor is defined inside the parent class, in this case Super (String s), the compiler will not insert the default parameterless constructor. This is the case for the parent class in the example above. The constructor of a subclass, whether with no arguments or arguments, invokes the parameterless constructor of the parent class. Because the compiler is trying to insert super () into the two constructors of a subclass. However, the default constructor 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, just like this:

?
123 publicSuper(){    System.out.println("Super");}

or 2) Remove the custom parent class constructor, or 3) call the parent class super (value) in the constructor of the child class. Constructor of Super and Sub

10. "" or a constructor?

There are two ways of constructing a string:

?
1234 //1. 利用双引号String x = "abc";//2. 利用构造函数String y = newString("abc");

What's the difference? The following example can give a quick answer:

?
123456789 String a = "abcd";String b = "abcd";System.out.println(a == b);  // TrueSystem.out.println(a.equals(b)); // TrueString c = new String("abcd");String d = new String("abcd");System.out.println(c == d);  // FalseSystem.out.println(c.equals(d)); // True

For more details about their memory allocations, refer to the Create Java String Using "or Constructor?

Work in the future

This list is for me based on a lot of open source projects on GitHub, problems on Stack overflow, and some common Google searches. There is no indication that the assessment shows that they are accurate in the top 10, but they are definitely a very common problem. If you do not agree to any part, please leave your comment. I would appreciate it if you could come up with some other common mistakes.

Translated from: Top Ten mistakes Java developers make

Http://www.cnblogs.com/liushaobo/p/4375493.html

Top Mistakes Java developers make (GO)

Related Article

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.