In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "what are the bug encountered in Java development", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the bug encountered in Java development?"
Catalogue
Error 1: converting Array to ArrayList
Error 2: check whether the array contains a value
Error 3: loop deleting elements in List
Error 4: Hashtable and HashMap
Error 5: using collections of primitive types
Error 6: access level problem
Error 7: ArrayList and LinkedList
Error 8: changeable and immutable
Error 9: constructor
Error 10: whether to use "" or constructor
Error 1: converting Array to ArrayList
Can you make mistakes when converting Array to ArrayList? This is not stupid.
Wait, wait.
If we were to convert an array to ArrayList, our general practice would be like this
List list = Arrays.asList (arr)
Arrays.asList () will return an ArrayList, which is a private static class in Arrays, not a java.util.ArrayList class. As shown in the following figure
The ArrayList inside Arrays has only set, get, contains and other methods, but there is no method like add that can change its internal structure, so the size of the ArrayList inside Arrays is fixed.
If you want to create an ArrayList that can add elements, you can use the following creation method:
ArrayList arrayList = new ArrayList (Arrays.asList (arr))
Because the constructor of ArrayList can accept a Collection collection, this method of creation is feasible.
Error 2: check whether the array contains a value
Check to see if the array contains a value, as some programmers often do:
Set set = new HashSet (Arrays.asList (arr)); return set.contains (targetValue)
This code is correct, but there is an additional performance penalty, and normally, you don't have to convert it to set, just do this:
Return Arrays.asList (arr) .resume (targetValue)
Or use the following method (exhaustive method, circular judgment)
For (String s: arr) {if (s.equals (targetValue)) return true;} return false
The first piece of code above is more readable than the second.
Error 3: loop deleting elements in List
I'm sure many of my buddies know that deleting elements in a loop is taboo, and for a while I liked to see if the rest of the team had made this mistake when reviewing the code.
After all, why can't you do this (delete elements from the collection)? Take a look at the following code
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)
Can you think of this output? Are you ready to try it?
The answer is actually [bmmel d]
Why are there only two values? Isn't this a circular output?
In fact, inside the list, when you use external remove, once you remove an element, the internal structure of the list will change. At the beginning, the total capacity of the collection is 4. Remove an element will become 3, and then compare with I. So you can only output two elements.
You may know that using iterators is the right way to use remove elements, and you may also know that for-each and iterator work similarly, so you wrote the following code
ArrayList list = new ArrayList (Arrays.asList ("a", "b", "c", "d")); for (String s: list) {if (s.equals ("a")) list.remove (s);}
And then your confident run xxx.main () method, the result. ConcurrentModificationException
Why is that?
That's because the use of external remove elements in ArrayList results in changes in its internal structure and cursors.
In the Ali development specification, there are also instructions not to remove/add elements within the for-each loop.
So if you want to use List to add or delete elements, be sure to use iterators to delete them. That is,
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 calls .next () after the operation to delete the element, resulting in ConcurrentModificationException.
Error 4: Hashtable and HashMap
This is an algorithmic specification: according to the algorithm, Hashtable is the name of the data structure, but in Java, the name of the data structure is HashMap,Hashtable and HashMap one of the main differences is that Hashtable is synchronous, so most of the time you do not need Hashtable, but use HashMap.
Error 5: using collections of primitive types
This is a generic constraint:
In Java, primitive types and unbounded wildcard types are easily mixed. In the case of Set, Set is the primitive type, while Set is the unbounded wildcard type.
For example, the following code uses the original type List as a 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);}
This code throws a java.lang.ClassCastException exception. Why?
Using primitive type collections is dangerous because primitive types skip generic checking and are not safe, Set, Set, and Set are very different, and generics can easily cause type erasure in use.
As we all know, Java generics are pseudo-generics, because all generics information is erased during compilation of Java. The first prerequisite for correctly understanding the concept of generics is to understand type erasure. Java generics are basically implemented at the compiler level, the generated bytecode does not contain type information in generics, type parameters are added when generics are used, and will be removed when the compiler compiles, and this process is called type erasure.
For example, defining types such as List and List in your code will become List,JVM after compilation. All you can see is List, but the type information attached by generics is not visible to JVM. The Java compiler will find possible errors as much as possible during compilation, but it is still unable to achieve type conversion exceptions at run time. Type erasing is also an important difference between Java generics and C++ template mechanism implementation.
For example, the following example
Public class Test {public static void main (String [] args) {ArrayList list1 = new ArrayList (); list1.add ("abc"); ArrayList list2 = new ArrayList (); list2.add (123); System.out.println (list1.getClass () = = list2.getClass ());}}
In this example, we define two ArrayList arrays, but one is of ArrayList generic type, which can only store strings; the other is of ArrayList generic type, which can only store integers. Finally, we get the information about their classes through the getClass () method of the list1 object and list2 object, and find that the result is true. Indicates that the generic types String and Integer have been erased, leaving only the original type.
So, in the top code, it's okay to add 10 to the Object type, but converting the "10" of the Object type to the String type throws a type conversion exception.
Error 6: access level problem
I believe that most developers will simply and rudely declare public xxx directly when designing class or member variables, which is a bad design, and it is easy to be naked when declared as public, which is dangerous for classes or member variables.
Error 7: ArrayList and LinkedList
Ha, ArrayList is one of the most frequently used tool classes I've ever seen programmers use.
When developers don't know the difference between ArrayList and LinkedList, they often use ArrayList (in fact, even if they do, they don't use LinkedList because the performance is not worth mentioning), because ArrayList looks more familiar.
But in fact, there is a huge performance difference between ArrayList and LinkedList, and in short, if there are a large number of add / remove operations and not many random access operations, LinkedList should be preferred. If there are a large number of access operations, then ArrayList is preferred, but ArrayList is not suitable for a large number of add / remove operations.
Error 8: changeable and immutable
Immutable objects have many advantages, such as simplicity, security and so on. But immutable objects need to allocate a separate object for each different value, the object does not have reusability, if there are too many such objects, it may lead to high cost of garbage collection. There needs to be a balance when choosing between mutable and immutable.
In general, mutable objects are used to avoid producing too many intermediate objects. For example, you have to concatenate a large number of strings. If you use an immutable string, you will produce a lot of objects that can be garbage collected immediately. This wastes CPU's time and effort, and using mutable objects is the right solution (such as
String result= "; for (String s: arr) {result= result + s;}
Therefore, the correct choice of mutable objects or immutable objects needs to be carefully chosen.
Error 9: constructor
First of all, take a look at a piece of code to analyze why the compilation failed.
This compilation error occurs because the constructor for the default Super is not defined. In Java, if a class does not define a constructor, the compiler defaults that the class inserts a default no-argument constructor. If a constructor is defined in the Super class, in this case Super (String s), the compiler will not insert the default no-argument constructor. This is the case with the Super class above.
To solve this problem, you just need to add a no-argument constructor to the Super.
Public Super () {System.out.println ("Super");} error 10: whether to use "" or constructor
Consider the following code:
String x = "abc"; String y = new String ("abc")
Is there any difference between the above two codes?
Maybe the following code will give you an answer.
String a = "abcd"; String b = "abcd"; System.out.println (a = = b); / / TrueSystem.out.println (a.equals (b)); / / True String c = new String ("abcd"); String d = new String ("abcd"); System.out.println (c = = d); / / FalseSystem.out.println (c.equals (d)); / / True
This is a typical memory allocation problem.
At this point, I believe you have a deeper understanding of "what are the bug encountered in Java development?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.