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 most common mistakes made by Java developers

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what mistakes Java developers make most often". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deeper to study and learn "what mistakes Java developers make most often" together!

Array to ArrayList

When it comes to converting Array to ArrayList, developers often do this:

List list = Arrays.asList(arr);

Arrays.asList() returns an ArrayList, but note that this ArrayList is a static inner of the Arrays class, not a java.util.ArrayList class. java.util.Arrays.ArrayList class implements set(), get(), contains() methods, but does not implement methods to add elements (in fact, you can call the add method, but there is no specific implementation, just throw UnsupportedOperationException exception), so its size is fixed. To create a real java.util.ArrayList, you should do this:

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

ArrayList's constructor can accept a Collection type, and java.util.Arrays.ArrayList already implements that interface.

Determine whether an array contains a value

Developers often do this:

Set set = new HashSet(Arrays.asList(arr));return set.contains(targetValue);

The above code works fine, but there is no need to convert it to a set collection. It takes extra time to convert a List to a Set. In fact, we can simply use the following method:

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

or

for(String s: arr){ if(s.equals(targetValue)) return true;}return false;

The first method is more readable.

Delete an element from the List inside the loop

Consider the following code to delete elements during iteration:

ArrayList list = new ArrayList(Arrays.asList("a", "b", "c","d"));for (int i = 0; i < list.size(); i++) { list.remove(i);}System.out.println(list);

Print Results:

[b, d]

There is a series of problems with this method above. When an element is deleted, the list size decreases and the original index points to another element. So if you want to delete multiple elements in a loop by indexing, it won't work correctly.

You probably know that iterators are the right way to delete elements in loops, and you probably know that foreach loops are similar to iterators, but that's not the case.

ArrayList list = new ArrayList(Arrays.asList("a", "b", "c","d"));for (String s : list) { if (s.equals("a")) list.remove(s);}

ConcurrentModificationException will be thrown.

However, the following code is OK:

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

The next() method needs to be called before the remove() method, and in the foreach loop, the compiler calls the next method after the delete element operation, which causes a ConcurrentModificationException exception. For more details, check out the source code for ArrayList.iterator().

HashTable and HashMap

From an algorithmic perspective, HashTable is the name of a data structure. But in Java, this data structure is called a HashMap. One of the main differences between a HashTable and a HashMap is that HashTables are synchronous, so usually you'd use HashMaps instead of HashTables.

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap Top 10 questions about Map

Use raw type of collection

In Java, raw types and unbounded wildcard types are easily confused. For example, Set is a primitive type and Set is an unbounded wildcard type.

Look at the following code. The add method takes a List of primitive type as an input parameter:

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

Running the above code will throw an exception:

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

Using primitive type collections is dangerous because it skips generic type checking and is unsafe. In addition, Set, Set, and Set are very different, see: type erasure and Raw type vs. Unbounded wildcard.

access level

Developers often use public to decorate a class field, and while it's easy for someone to get the field's value directly by reference, it's a bad design. As a rule of thumb, the access level of member attributes should be lowered as much as possible.

Public, default, protected, and private

ArrayList and LinkedList

Why do developers often use ArrayList and LinkedList without knowing the difference between them because they look alike? However, there are huge performance differences between them. Simply put, LinkedList should be preferred if there are a lot of add and delete operations and not a lot of random access to elements.

variable and immutable

Immutable objects have many advantages, such as simplicity, security and so on. But a separate object is needed for each different value, and too many objects cause a lot of garbage collection, so there needs to be a balance between mutability and immutability.

Often, mutable objects are used to avoid creating large numbers of intermediate objects, a classic example being concatenation of large numbers of strings. If you use an immutable object, you will immediately generate a large number of objects that meet garbage collection standards, which wastes a lot of CPU time and effort. Using mutable objects is the correct solution (StringBuilder);

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

In addition, there are other situations where mutable objects are needed. For example, pass a mutable object into a method and collect multiple results without having to

Write too much grammar. Another example is sorting and filtering: of course, you could write a method that takes the original set and returns a sorted set, but that would be too wasteful for large sets.

Why we need mutable classes?

Constructors of parent and child classes

This compilation error occurs because the default constructor for the parent class is undefined. In Java, if a class does not define a constructor, the compiler will insert a parameterless constructor by default; but if a constructor is defined in the parent class, in this case, the compiler will not automatically insert a default parameterless constructor, which is the case with demo above;

For subclasses, both parameterless and parameterless constructors call the parameterless constructor of the parent class by default; when the compiler tries to insert super() methods into these two constructors in a subclass, the compiler reports an error because the parent class does not have a default parameterless constructor;

To fix this error, it is simple:

1. Manually define a parameterless constructor method in the parent class:

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

2. Remove custom constructor methods from parent class

3. Write the call to the parent class constructor method in the subclass itself; such as super(value);

"" or construction method

There are two ways to create strings:

//1. use double quotesString x = "abc";//2. use constructorString y = new String("abc");

What's the difference between them?

The following code provides a quick answer:

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

Thank you for reading, the above is "Java developers have what the most common mistakes" content, after the study of this article, I believe we have a deeper understanding of Java developers what the most common mistakes this problem, the specific use of the situation also needs to be verified. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

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

Development

Wechat

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

12
Report