The 10 most common mistakes Java programmers make are __java

Source: Internet
Author: User
Tags data structures garbage collection concurrentmodificationexception

Err, you can never have. It is said that the Java language is a simple programming language, based on the evolution of C + +, eliminating many complex features in C + +, but this does not guarantee that Java programmers do not make mistakes. So for the vast majority of Java programmers, what are the 10 most common mistakes they make?

By summarizing the 10 big mistakes that Java programmers make most often, this article can effectively help group Java followers less detours, less overtime, and write more robust applications.


Array to ArrayList  

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, rather than a common java.util.ArrayList class. This java.util.Arrays.ArrayList class has a set (), a Get (), A contains (), and so on, but does not have any methods to add or remove elements. Because the size of the class is fixed. In order to create a real java.util.ArrayList, the code should look like the following:

arraylist<string> ArrayList = new Arraylist<string> (Arrays.aslist (arr));
We know that the ArrayList construction method can accept an object of collection type, and our java.util.Arrays.ArrayList is exactly one of its subclasses. In fact, a more efficient code example is:
arraylist<string> ArrayList = new arraylist<string> (arr.length);
 Collections.addall (ArrayList, arr);

The results of the operation are shown below:

To check whether the array contains a particular value, many Java programmers use the following code:

set<string> set = new Hashset<string> (Arrays.aslist (arr));

Return Set.contains (Targetvalue);
In terms of functionality, the code is correct, but it consumes a lot of performance while the array is list,list and then turned to set. We can optimize into the following form:
Arrays.aslist (arr). Contains (Targetvalue);
Or, further optimization is the most efficient code shown below:
for (String S:arr) {
   if (s.equals (Targetvalue)) return
       true;
}
return false;

The results of the operation are shown in the following illustration:




First, look at the code that removes the elements in the list 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 sample code is:

[B,d]

There is a very serious error in this example code. When an element is removed, the size of the list is reduced and the index is pointed. Therefore, using an index during an iteration will make it impossible to correctly delete multiple specified elements from the list.

One of the ways you may know to solve 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 sample code:

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

This example code throws out a concurrentmodificationexception. We should modify it as follows:

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 ()//note here
    }
}

The. Next () method must be invoked before the Remove () method. In a foreach loop, the compiler causes the Remove () method to be invoked before the next () method, which results in a concurrentmodificationexception exception. Specific details can be viewed arraylist.iterator () source.



Readers who have studied data structures know that a very important data structure is called a hash table. In Java, the classes that correspond to a hash table are hashmap rather than Hashtable. The most important difference between HashMap and Hashtable is:

The HashMap is unsynchronized and the Hashtable is synchronized.



In Java, the original type is easily blended with the unbounded wildcard type, and for set, set is an original type, and Set<?> is an unbounded wildcard type.
The following code uses the original type list as the code for the 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 piece of code throws an exception:
Exception in thread "main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String at
    ...
Using the original type in collection is risky with many types of errors because the original type does not have a static type check. In fact, there is a very large difference between Set, set<?>, and set<object>.


Many Java beginners like to use public to decorate 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 correct design style should be to minimize the access rights of class members.



Many Java beginners do not understand the difference between ArrayList and LinkedList, so they simply use relatively simple ArrayList, not even knowing that there are linkedlist in the JDK.

However, in some specific scenarios, the choice of these two lists can lead to great differences in program performance. In simple terms: when there are many add/remove operations in the application scene, only a small number of random access operations, you should choose LinkedList, in other scenarios, consider the use of ArrayList.



Immutable objects have a lot of 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 mutable class or an immutable class, you should make a comprehensive consideration before making a choice.


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 immutable string classes, the linked 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, it is correct to use a variable StringBuilder or stringbuffer.

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

In addition to the above, mutable objects may be used in other scenarios for immutable objects. For example, passing a mutable object into a method allows you to collect multiple results without jumping in and out of multiple loop hierarchies.



The two compile-time errors that appear in the previous illustration are because the default constructor is not defined in the parent class, and the default constructor for the parent class is called in the subclass. In Java, if a class does not define any constructors, the compilation period automatically inserts a default constructor into the class. Once a class defines any constructor, the compilation period does not insert any constructors into the class. In the above example, the Super class defines a constructor with a parameter type of string, so there is only one constructor in the class and there is no default constructor.


&emps; in our sub class sub, we define two constructors: one constructor with a parameter type string and the other the default function for lunch. Since neither of them specifies the constructor of the calling parent class in the first row of the function body, they all need to invoke the default constructor of the parent class Super. However, the default constructor for the parent class Super does not exist, so the compiler reports both error messages.



There are two ways to create a string:

1. Use string
x = "abc";
2. Use the constructor
string y = new String ("abc");
What's the difference.
The following example gives a quick answer:
String a = "abc";
String B = "abc";
System.out.println (a==b);//true
System.out.println (a.equals (b));//true
 
string c = new String ("abc")
; String d = new String ("abc");
System.out.println (C==d);//false
System.out.println (c.equals (d));//true

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.