Ten common errors made by Java developers

Source: Internet
Author: User
Tags concurrentmodificationexception

Ten common errors made by Java developers
This article lists the most common errors made by Java developers. 1. to convert an array to an ArrayList, developers often do this: List <String> list = Arrays. asList (arr); Arrays. asList () returns an ArrayList, but this ArrayList is the Private Static class of Arrays, not java. util. arrayList. Java. util. Arrays. ArrayList has the set (), get (), and contains () methods, but there is no method to add elements, so its size is determined. To create a real ArrayList, we should do this: ArrayList <String> arrayList = new ArrayList <String> (Arrays. asList (arr); the constructor of ArrayList can receive a Collection type, which is also java. util. arrays. an ancestor class of ArrayList. 2. check whether an array contains a specific value. Developers often do this: Set <String> set = new HashSet <String> (Arrays. asList (arr); return set. contains (targetValue); this code can work, but there is no need to first convert the array to a set. It takes additional time to convert the array to a set. You can do this: Arrays. asList (arr ). contains (targetValue); or for (String s: arr) {if (s. equals (targetValue) return true;} return false; the first one is more readable than the second one. 3. the following code deletes the list elements in a loop. This Code deletes the ArrayList element <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); [B, d] the above method has a serious problem. When an element is removed, the size of the List decreases and the index changes. Therefore, it is impossible to delete multiple elements in a loop using indexes. You may know that using the iterator to delete elements in a loop is the correct method, and you know that the Java foreach loop is like an iterator, but in fact it is not. Think about 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);} It will throw ConcurrentModificationException. The following code is acceptable: 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 ();}}. the next () method must be called. called before the remove () method. In the foreach loop, the compiler first calls. remove () and then. next (), resulting in ConcurrentModificationException. You may want to know the source code of ArrayList. iterator. 4. HashTable vs HashMap according to the algorithm conventions, HashTable is the name of this data structure, but in Java, HashMap is the name of this data structure. A key difference between Hashtable and HashMap is that HashTable is synchronous, but HashMap is not. Therefore, HashTable is usually not required, and HashMap uses more. HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap Top 9 questions about Java Maps 5. Use the original set type in Java. The original type and the unbounded wildcard type are easily mixed. Taking Set as an example, Set is an original type, and Set <?> Is an unbounded wildcard type. The following code uses the original type List as the parameter: 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, 10 ); string s = list. get (0);} the above Code will throw an Exception: Exception in thread "main" java. lang. classCastException: java. lang. integer cannot be cast to java. lang. string... it is dangerous to use the original set type because the original set type skips the generic type check, which is not safe. Set, Set <?> There is a big difference between it and Set <Object>. See Raw type vs. Unbounded wildcard and Type Erasure. 6. Access-level developers often use Public as class modifiers, which can be easily obtained through direct reference, but this is a very bad design. Based on experience, the access level allocated to members should be as low as possible. Public, default, protected, and private 7. ArrayList vs protected list when developers do not know the difference between ArrayList and protected list, ArrayList is usually used because it looks more familiar. However, there are major performance differences between the two. To put it simply, when there are a large number of insert/delete operations without too many random access operations, you should use the shortlist. If you are not familiar with this, refer to ArrayList vs. Rule List. 8. mutable and immutable objects have many advantages, such as simplicity and security. However, each value must have an independent object. Excessive objects cause high consumption of garbage collection. There should be a trade-off between variable selection and immutable selection. Generally, a variable object can be used to avoid generating too many intermediate objects. A classic instance is used to connect a large number of strings. If an immutable string is used, a large number of objects that require garbage collection will be generated. This wastes a lot of time on the CPU. Using a mutable object is the correct solution (such as StringBuilder ). String result = ""; for (String s: arr) {result = result + s;} variable objects are also required in other cases, for example, passing a variable object as a parameter allows you to get multiple results without using many statements. Another example is sorting and filtering: Of course, you can write a method to receive the original set and return a sorted set, but it is too wasteful for a large set. (Answer from dasblinkenlight of StackOverFlow ). Why String is Immutable? 9. The constructor of the parent class and subclass does not define the default constructor of the parent class, and errors will occur during compilation. In Java, if a class does not define a constructor, the compiler inserts a default constructor without parameters. If a constructor is defined in the parent class, in this example, Super (String s), the compiler will not insert the default non-parameter constructor. This is the case of the parent class in the above example. The subclass constructor calls the non-argument constructor of the parent class no matter there are no parameters or parameters. The compiler tries to insert super () into the two constructors of the subclass. However, if the default constructor of the parent class is undefined, the compiler reports this error message. To fix this problem, you can simply add a Super () constructor to the parent class, like this: public Super () {System. out. println ("Super");} or 2) Remove the custom parent class constructor, or 3) call the super (value) of the parent class in the constructor of the subclass ). Constructor of Super and Sub 10. "" or Constructor? There are two methods to construct a string: // 1. use double quotation marks String x = "abc"; // 2. use the constructor String y = new String ("abc"); what is the difference? The following example provides a quick answer: String a = "abcd"; String B = "abcd"; System. out. println (a = B); // TrueSystem. out. println (. 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 for more details about their memory allocation, see Create Java String Using "or Constructor? For future work, this list is obtained based on a large number of open-source projects on GitHub, problems on Stack Overflow, and some common Google searches. No clearly-displayed evaluations prove that they are the top 10 accurate, but they are definitely very common. If you do not agree to any score, please leave your comment. I am very grateful if you can make other common errors.

Related Article

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.