In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the common mistakes made by Java programmers". In daily operation, I believe that many people have doubts about the common mistakes made by Java programmers. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "what are the common mistakes made by Java programmers?" Next, please follow the editor to study!
01. Convert Array to ArrayList
To be honest, many Java programmers like to convert Array to ArrayList:
List list = Arrays.asList (arr)
But in fact, the ArrayList returned by Arrays.asList () is not java.util.ArrayList, but the internal private class java.util.Arrays.ArrayList of Arrays. Although the names are exactly the same, both are ArrayList, but the two classes are very different. Although Arrays.ArrayList has methods such as set (), get (), and contains (), there is no method for adding elements, so its size is fixed.
If you want to create a real ArrayList, do this:
List list = new ArrayList (Arrays.asList (arr))
The constructor of ArrayList can take a parameter of type Collection, and Arrays.ArrayList is a subclass of it, so it can be converted in this way.
02. Check whether the array contains a certain value through Set
Methods:
Set set = new HashSet (Arrays.asList (arr)); return set.contains (targetValue)
This approach does work, but ignores performance issues; in order to complete the check as soon as possible, you can do this:
Arrays.asList (arr) .resume (targetValue)
Or use a normal for loop or for-each.
03. Delete elements in the list through the for loop
Novice special columns like to use for loops to delete elements from the list, like this:
List list = new ArrayList (Arrays.asList ("Shen", "Mo", "Wang", "II"); for (int I = 0; I < list.size (); iTunes +) {list.remove (I);} System.out.println (list)
The purpose of the above code is to delete all the elements in the list, but as a result:
[Mo, II]
There are still two elements left to delete, why?
When an element of List is deleted, its size () decreases and the subscript of the element changes, so it is impossible to delete the element through the for loop.
What about for-each?
For (String s: list) {if ("Shen" .equals (s)) {list.remove (s);}} System.out.println (list)
Unexpectedly, an exception was thrown:
Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification (ArrayList.java:909) at java.util.ArrayList$Itr.next (ArrayList.java:859) at com.cmower.java_demo.programcreek.Top10Mistake.main (Top10Mistake.java:15)
If you throw the reason for the exception, you can check out my previous article, "Java, can you tell me what the devil fail-fast is?"
Experienced programmers should already know the answer, using Iterator:
Iterator iter = list.iterator (); while (iter.hasNext ()) {String s = iter.next (); if (s.equals (sinking)) {iter.remove ();}} System.out.println (list)
The result of the program output is as follows:
[Mo, Wang, II]
04. Use Hashtable instead of HashMap
Generally speaking, the hash table should be Hashtable, but in Java, the hash table usually refers to HashMap. One of the differences between the two is that Hashtable is thread safe. If there are no special requirements, the hash table should use HashMap instead of Hashtable.
Use the original type
In Java, it's easy for beginners to confuse the difference between infinite wildcards and primitive types. For example, List list is an infinite wildcard and List list is a primitive type.
Take a look at the following code:
Public static void add (List list, Object o) {list.add (o);} public static void main (String [] args) {List list = new ArrayList (); add (list, 18); add (list, Silent King II); String s = list.get (0);}
This code throws an exception at run time:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at com.cmower.java_demo.programcreek.Top10Mistake.main (Top10Mistake.java:38)
Using primitive types is very dangerous because generics are skipped. As for the difference between List and List, take a look at another article I wrote, "Why shouldn't you use the primitive type of Java?"
06. Use public to decorate fields
Some beginners like to use public to decorate fields because they can be accessed without the need for getter/setter methods. But in fact, this is a very bad design; experienced programmers are more used to providing the lowest possible level of access.
07. Use ArrayList instead of LinkedList
Beginners often don't know the difference between ArrayList and LinkedList, so they prefer to use ArrayList because they look familiar. However, there are huge performance differences between them. To put it simply, if there are more add / remove operations and fewer get operations, LinkedList should be preferred.
08. Too many immutable objects are used
Immutable objects have many advantages, such as simplicity and security. However, as you might expect, it also has some irresistible disadvantages: for each different value, it needs a separate object to represent it. If there are too many such objects, it is likely to lead to a large amount of garbage, and the cost of recycling becomes particularly high.
In order to maintain a balance between mutable and immutable, mutable objects are usually used to avoid producing too many intermediate objects. A classic example is to use StringBuilder (mutable objects) to concatenate a large number of strings, otherwise String (immutable objects) will produce a lot of garbage to be recycled.
Counterexample:
String result= "; for (String s: arr) {result= result + s;}
Positive example:
StringBuilder result = new StringBuilder (); for (String s: strs) {result.append (s);}
Reference article: why Java strings are immutable?
09. The parent class has no default no-parameter construction method
In Java, if the parent class does not define a constructor, the compiler inserts a no-parameter constructor by default; however, if a constructor is defined in the parent class, the compiler no longer inserts a no-parameter constructor. So the following code will go wrong at compile time.
The no-parameter constructor in the subclass attempts to call the no-parameter constructor of the parent class, but it is not defined in the parent class, so there is an error in the compilation. The solution is to define a no-parameter constructor in the parent class.
10. Use the constructor to create a string
There are two ways to create a string:
1) use double quotation marks
String er = "Silent King II"
2) use the construction method
String san = new String (Silent King III)
But there is a big difference between them. Double quotes are called string constants, and strings that repeat content can be avoided being created in memory.
At this point, the study on "what are the common mistakes made by Java programmers" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.