10 errors that Java programmers often make

Source: Internet
Author: User
Tags concurrentmodificationexception

This article summarizes the 10 errors that Java programmers often make.

#1. Convert the array into ArrayList

To convert an array into ArrayList, programmers often use the following methods:

list<string> list = Arrays.aslist (arr);

Arrays.aslist () actually returns a ArrayList, but this ArrayList is an internal private class of Arrays, not a java.util.ArrayList class. This private class java.util.Arrays.ArrayList has set (), Get (), contains () methods, but cannot add new elements. The size of it is fixed. If you want a java.util.ArrayList, the right way is:

arraylist<string> ArrayList = new Arraylist<string> (Arrays.aslist (arr));

The Java.util.ArrayList constructor can accept a collection type. Java.util.Arrays.ArrayList also inherits the collection type, so it can be used as a function parameter.

#2. Checks if an array contains a value

What developers often do is:

set<string> set = new Hashset<string> (Arrays.aslist (arr)); return Set.contains (Targetvalue);

This code is working, but not inefficient. It is not necessary to convert the list to set, which requires additional time. The correct method is:

Arrays.aslist (arr). Contains (Targetvalue);

Or, a simple loop:

for (String S:arr) {if (S.equals (Targetvalue)) return true;} return false;

The first type is more readable than the second.

#3. Delete a list element in a loop

Consider the following code, which removes the element during the iteration:

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 of this code is:

[B, D]

There is a serious problem with this method. When the element is removed, the size of the list is reduced and the index of the element changes. Therefore, if you want to delete multiple elements within a loop by using an index, you will result in an incorrect result.

You might guess that you can use iterator to delete elements in a loop. The Foreach Loop in Java works like a iterator. But there will also be errors here. Take a look at the following code:

arraylist<string> list = new Arraylist<string> (Arrays.aslist ("A", "B", "C", "D")); for (String s:list) {if (S.equals ("a")) List.remove (s);}

The Foreach Loop code above throws an exception concurrentmodificationexception. But the following code does not.

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

By analyzing the original Code of Arraylist.iterator (), we can see that the next () method must be called before the Remove () method. In a foreach loop, the code produced by the compiler calls the next () method, resulting in an exception concurrentmodificationexception. Please see the original code for Arraylist.iterator ().

#4. Hashtable and HashMap

According to the algorithm convention, Hashtable is the name of the data structure. In Java, however, the name of the data structure is hashmap. The Hashtable is a synchronous version. So many times you don't need Hashtable, but hashmap. These two articles detail the different map differences and common problems: HashMap vs. TreeMap vs. Hashtable vs. Linkedhashmap, map Common 10 major problems,

#5. Using the original type collection

In Java, primitive types and unbounded wildcard types are easily mixed together. In set, for example, set is the original type, and Set<?> is an unbounded wildcard type.

Consider the following code, which uses the list of the original type as a parameter:

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);}

This code throws an exception:

Exception in thread "main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to Java.lang.Stringat ...

It is dangerous to use collection of the original type, because the collection of the original type is skipped for type checking. Also worth mentioning is Set, set<?> there is a huge difference between set<object>. To learn more, see original type vs. unbounded wildcard types and type erasure.

#6. Access level

Many times, developers use the public to modify fields. The benefit of this is that it is easy to get the value of a field by direct reference, but this is a very bad design. The rule of thumb is "to give members access levels as low as possible." You can view Java4 different access levels public, default, protected, and private.

#7. ArrayList and LinkedList

When developers don't know the difference between ArrayList and LinkedList, they often use ArrayList, probably because it looks familiar. But there is a huge difference in performance between ArrayList and LinkedList. Simply put, if there is a large number of Add/delete operations, and there are not many random access operations, LinkedList should be preferred. You can view ArrayList and LinkedList to learn more about the differences between them.

#8. Variability and invariance

Immutable objects have many advantages, such as simplicity, security, and so on. But it needs to create a separate object for each of the different values, and too many objects can lead to a high cost of garbage collection. So there should be a balance between variable and immutable choices.

In general, use mutable objects to avoid producing too many intermediate objects. A classic example is the concatenation of a large number of strings. If you are using a string that is immutable, it produces many objects that can be garbage collected. This wastes both time and CPU computing power, and using mutable objects is the correct solution (such as StringBuilder).

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

In other cases, mutable objects are just more appropriate. For example, sort (Collections.sort ()). If the collection is immutable, the sorting method will return a new collection each time, which can be extremely wasteful of resources. Can you see why string is designed to be immutable in Java?

#9. Constructors for parent and child classes

The above code has a compilation error because the default parent class constructor is undefined. In Java, if a class does not have a constructor defined, the compiler inserts a default parameterless constructor by default. If the programmer defines a constructor, the compiler will not insert the default parameterless constructor. The code above is no longer inserted into the parameterless constructor because it customizes the constructor with parameters. The constructor of a subclass, whether with parameters or no arguments, calls the parent class without a parameter constructor. An error occurred when the subclass needed a parameterless constructor for the parent class.

To solve this problem, you can 1) add a parent class constructor

Public Super () {    System.out.println ("Super");}

, or 2) Delete the custom parent class constructor, or 3) add super (value) to the subclass constructor. See the constructors of the parent and child classes for more information.

#10. "With Constructor?"

Strings can be created in two ways:

1. Use double quotesstring x = "abc";//2. Use constructorstring y = new String ("abc");

What is the difference between the two? The following example can provide a quick answer:

String a = "ABCD"; String B = "ABCD"; System.out.println (A = = B);  TrueSystem.out.println (A.equals (b)); True string c = new String ("ABCD"); String d = new String ("ABCD"); System.out.println (c = = d);  FalseSystem.out.println (C.equals (d)); True

For more information on how they allocate memory, see Creating Java Strings using the "" or constructors?

Summary

These are my summaries of the issues on the open source project on GitHub, Stack overflow, and Google's top search terms. Although they are not accurate top 10, they are very common. If you have a different point of view or point out more common mistakes, please leave a message. I will also update this list. Thank you so much.

Top Ten mistakes Java developers make

10 errors that Java programmers often make

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.