Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ten mistakes that Java developers are likely to make?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the ten mistakes that Java developers are easy to make". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the ten mistakes that Java developers are easy to make.

Top1. Convert array to array list

Convert an array to an array list, as developers often do:

[java]

List list = Arrays.asList (arr)

Arrays.asList () returns an ArrayList with a private static class inside the array, which is not a java.util.ArrayList class. The java.util.Arrays.ArrayList class has set (), get (), and contains () methods, but there are no methods to add elements, so its size is fixed. Can be used to facilitate the conversion of list, can not add new elements, so choose the correct usage scenario.

You can also do this to create a real array:

[java]

ArrayList arrayList = new ArrayList (Arrays.asList (arr))

The constructor of ArrayList can accept a collection type, which is also the super type of java.util.Arrays.ArrayList.

Top2. Check that an array contains a value

Developers often do this:

[java]

Set set = new HashSet (Arrays.asList (arr))

Return set.contains (targetValue)

The code works, but it's not necessary to convert the list to Set first. It takes extra time to convert a list to a Set. So you can simplify it to:

[java]

Arrays.asList (arr) .resume (targetValue)

Or

[java]

For (String s: arr) {

If (s.equals (targetValue))

Return true

}

Return false

The first one is more readable than the second.

Top3. Delete an element from a list in a loop

Consider the following iterative result of the code that deletes the element:

[java]

ArrayList list = new ArrayList (Arrays.asList ("a", "b", "c", "d"))

For (int I = 0; I < list.size (); iTunes +) {

List.remove (I)

}

System.out.println (list)

The output is:

[java]

[b, d]

A serious problem with this approach is that when an element is deleted, the size of the list contraction and the pointer change. So it is impossible to delete multiple elements using pointers within a loop.

Using an iterator is the right approach in this case. The foreach loop works like an iterator in Java, but it's not. Consider the following code:

[java]

ArrayList list = new ArrayList (Arrays.asList ("a", "b", "c", "d"))

For (String s: list) {

If (s.equals ("a"))

List.remove (s)

}

It reports a ConcurrentModificationException exception.

On the contrary, the following one will work properly.

[java]

ArrayList list = new ArrayList (Arrays.asList ("a", "b", "c", "d"))

Iterator iter = list.iterator ()

While (iter.hasNext ()) {

String s = iter.next ()

If (s.equals ("a")) {

Iter.remove ()

}

}

.next () must be called before .remove (). In the foreach loop, the compiler will call .next () after the delete element operation, 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 general rules of the algorithm, Hashtable is a term for data structures. But in Java, the name of the data structure is HashMap. One of the key differences between Hashtable and HashMap is that Hashtable is synchronous.

Top5. Use the original type of the collection

In Java, primitive types and unrestricted wildcard types are easily confused. Take Set as an example, Set is the primitive type, while Set (?) Is an unrestricted wildcard type.

Consider the following code, which takes a primitive type List as a parameter:

[java]

Public static void add (List list, Object o) {

List.add (o)

}

Public static void main (String [] args) {

List list = new ArrayList ()

Add (list, 10)

String s = list.get (0)

}

The code throws an exception:

[java]

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

At...

It is dangerous to use primitive type collections because they skip generic type checking and are not safe. There is a big difference between Set, Set, and Set.

Top6. Access level

Developers often use public for class domains, which makes it easy to get domain values through direct references, but this is a very bad design. As a rule of thumb, the lower the access level given to members, the better.

For more information, please click to view the access level of members in Java (please click "read original"): 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 are huge performance differences between them. To put it simply, LinkedList should be your first choice if there are a large number of add / delete operations and not many random access operations. If you don't know much about this, click here for more information about their performance.

Top8. Mutable VS Immutable

Immutable objects have many advantages, such as simplicity, security, and so on. But it requires that each different value needs a different object, and too many objects can lead to high cost of garbage collection. So there should be a balance between Mutable and Immutable.

In general, Mutable objects are used to avoid producing too many intermediate objects, and a classic example is to concatenate a large number of strings. If you use Immutable strings, there will be a lot of objects that meet the garbage collection criteria. This is a waste of time and effort for CPU when it can use the Mutable object as the right solution. (e.g. StringBuilder)

[java]

String result= ""

For (String s: arr) {

Result = result + s

}

There are also some other desirable situations for Mutable objects. For example, passing a mutable object to a method allows you to collect multiple results without skipping too much syntax. Another example is sorting and filtering, where you can build a method with the original collection and return an ordered one, but this is more wasteful for large collections.

Top9. Super and Sub constructor

This compilation error is because the default Super constructor is undefined. In Java, if a class does not define a constructor, the compiler inserts a no-argument constructor for the class by default. If a constructor is defined in the Super class, in this case Super (String s), the compiler does not insert the default no-argument constructor.

On the other hand, the constructor of the Sub class, with or without arguments, calls the parameterless Super constructor.

The compiler tries to insert Super () into two constructors in the Sub class, but the compiler reports an error only if the default constructor for Super is not defined. How to solve this problem? You just need to add a Super () constructor to the Super class, as follows:

[java]

Public Super () {

System.out.println ("Super")

}

Either remove the custom Super constructor, or add super (value) to the Sub function.

Top10. "" or constructor?

Strings can be created in two ways:

[java]

/ / 1. Use double quotes

String x = "abc"

/ / 2. Use constructor

String y = new String ("abc")

What's the difference between them? The following example gives the answer:

[java]

String a = "abcd"

String b = "abcd"

System.out.println (a = = b); / / True

System.out.println (a.equals (b)); / / True

String c = new String ("abcd")

String d = new String ("abcd")

System.out.println (c = = d); / / False

System.out.println (c.equals (d)); / / True Thank you for reading. The above is the content of "what are the Ten mistakes easy to make by Java developers". After studying this article, I believe you have a deeper understanding of what are the ten mistakes that Java developers are easy to make, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report