10 errors that Java programmers can easily make

Source: Internet
Author: User

1. Array Turn ArrayList

General developers like to use:

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

Arrays.aslist () returns a ArrayList, which is a private static class embedded in Arrays, not Java.util.ArrayList class Java.util.Arrays.ArrayList has set (), get (), The contains () method, but also supports adding elements, so the size is fixed and you want to create a real ArrayList, you should:

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

For more explanations of this method, please see my previous article

Http://www.cnblogs.com/tina-smile/p/5056174.html

2. Detects if an array contains an element

General developers like to use:

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

This code works, but without first turning the list to Set,list to set takes extra time and can be simpler with the following:

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

Or

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

The first method is more readable than the second.

3. Remove elements from list in a loop

Consider the following approach:

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

Expected output is [B, d]

But there is a serious problem with this approach, and when an element is removed, the size of the list shrinks and the index changes. So if you want to use an index to remove multiple elements in a loop, this is not feasible.

Perhaps you want to solve this problem in the way of iterators, but it is not practical, consider 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);}

Will error concurrentmodificationexception.

The correct one should be:

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 ();}    }
4. Hashtable vs HashMap

In the algorithm, the hash table is the name of the data structure. In Java, however, the name of the data structure is hashmap. One of the main differences between Hashtable and HashMap is that Hashtable is synchronous. So, most of the time, you don't need a hash table, HashMap is enough.

5. Use the collection of the original type

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

Using the original Type list, consider the following scenario:

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, ten);    String s = list.get (0);}

This code will throw an error:

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

Using the collection of primitive types is a dangerous thing, because it skips class property detection and is unsafe. Set, Set<?>, and set

6. Access rights

Many developers use the public to modify the fields of the class, which makes it easy to get field values, but this is a bad design. The rule of thumb is to give the user the lowest possible access rights.

7.ArrayList vs. LinkedList

Most developers don't know the difference between ArrayList and LinkedList, so they often use ArrayList, which looks more familiar. However, there is a big difference in performance between the two.

Simply put, LinkedList is recommended when there are many insertions and deletions, with little or no random access to the operation. Second, use ArrayList again.

8.Mutable vs. immutable (variable vs immutable)

Immutable objects have many advantages such as simplicity, security, and so on. But it requires a separate object for each variable. Too many objects can lead to high-cost garbage collection. So there should be a trade-off when choosing between mutable and immutable.

In general, use mutable objects to avoid producing too many intermediate objects. A classic example is the connection of a large number of strings. If you use an immutable string, you will generate many objects that are immediately reclaimed by garbage collection, which consumes time and effort. If you use an immutable, similar to StringBuffer.

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

There are other examples of mutable objects: in the process of function-passing, variable objects can be passed in, so that multiple results can be obtained.

9. Building a parent class and subclass

The main reason for compiling errors is that the default super class constructors are not defined. In Java, if a class does not implement a constructor, the compiler defaults to inserting an parameterless constructor into the class. If a constructor is already in the parent class, the compiler will no longer insert the default parameterless constructor.

The constructor of a subclass, either with or without a parameter, invokes the parent class's parameterless construct. Because the compiler wants to include super () in the subclass, the parameterless constructor for the parent class does not exist. Therefore, the compiler will error.

In order to solve this problem, there are two solutions, first, in the Super class, join the parameterless construct:

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

The second way to remove the custom parent constructor

The third way, the subclass's constructor joins super (value)

"" or Constructor?

There are two ways of creating a string:

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

What's the difference?

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

10 errors that Java programmers can easily make

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.