Five Most Common Errors in Java
Developers often encounter various inexplicable errors during programming. Recently, Sushil Das listed five common errors in Java Development On Geek On Java 」.
1. over-use of Null
It is a best practice to avoid over-using null values. For example, it is better to let the method return an empty array or collection instead of a null value, because this can prevent the program from throwing NullPointerException. The following code snippet obtains a set from another method:
List <String> accountIds = person. getAccountIds ();
For (String accountId: accountIds ){
ProcessAccount (accountId );
}
If a person does not have an account, getAccountIds () returns null, and the program throws an NullPointerException. Therefore, we need to add an empty check to solve this problem. If the returned null value is replaced with an empty list, NullPointerException will not appear. Besides, because we no longer need to check the variable accountId, the code will become more concise.
When you want to avoid null values, different scenarios may adopt different approaches. One method is to use the Optional type, which can be either an empty object or some value encapsulation.
Optional <String> optionalString = Optional. ofNullable (nullableString );
If (optionalString. isPresent ()){
System. out. println (optionalString. get ());
}
In fact, Java 8 provides a more concise method:
Optional <String> optionalString = Optional. ofNullable (nullableString );
OptionalString. ifPresent (System. out: println );
Java supports the Optional type since Java 8, but it is well known in the world of functional programming. Previously, it was used in earlier versions of Google Guava for Java.
2. Ignore exceptions
We often ignore exceptions. However, for beginners and experienced Java programmers, the best practice is to deal with them. Exception throws are usually purposeful, so you need to record the events that cause exceptions in most cases. Don't underestimate it. If necessary, you can throw it again, display the error information to the user in a dialog box, or record the error information in the log. At least, to let other developers know the cause and effect, you should explain why this exception was not handled.
Selfie = person. shootASelfie ();
Try {
Selfie. show ();
} Catch (NullPointerException e ){
// Maybe, invisible man. Who cares, anyway?
}
An easy way to emphasize that an exception is not important is to use this information as the variable name of the exception, as shown in the following code:
Try {selfie. delete ();} catch (NullPointerException unimportant ){}
3. concurrent modification exception
This exception occurs when the set object is modified and the content in the set is not updated using the method provided by the iterator object. For example, there is an hats list and you want to delete all values containing the ear flaps:
List <IHat> hats = new ArrayList <> ();
Hats. add (new Ushanka (); // that one has ear flaps
Hats. add (new Fedora ());
Hats. add (new Sombrero ());
For (IHat hat: hats ){
If (hat. hasEarFlaps ()){
Hats. remove (hat );
}
}
If you run this code, ConcurrentModificationException is thrown because the code traverses this set and modifies it. When multiple processes act on the same list, when one of the processes traverses the list, another process tries to modify the list content. The same exception may also occur.
It is very common to modify the set content concurrently in multiple threads. Therefore, you need to use common methods in concurrent programming, such as synchronization locks and special sets for concurrent modifications. There is a slight difference between Java and multithreading in solving this problem.
Collect objects and delete them in another loop
The direct solution is to put the hats with ear flaps into a list, and then delete it in another loop. However, this requires an additional set to store the hats to be deleted.
List <IHat> hatsToRemove = new external List <> ();
For (IHat hat: hats ){
If (hat. hasEarFlaps ()){
HatsToRemove. add (hat );
}
}
For (IHat hat: hatsToRemove ){
Hats. remove (hat );
}
Use the Iterator. remove Method
This method is simpler and does not need to create additional sets:
Iterator <IHat> hatIterator = hats. iterator ();
While (hatIterator. hasNext ()){
IHat hat = hatIterator. next ();
If (hat. hasEarFlaps ()){
HatIterator. remove ();
}
}
ListIterator Method
When the set to be modified implements the List interface, list iterator is a very suitable choice. The iterator that implements the ListIterator interface supports not only the delete operation, but also the add and set operations. The ListIterator interface implements the Iterator interface, so this example looks like the Iterator remove method. The only difference is that the type of the hat iterator and the way we get the iterator -- use the listIterator () method. The following snippet shows how to use the ListIterator. remove and ListIterator. add methods to replace hat with ear flaps with sombreros.
IHat sombrero = new Sombrero ();
ListIterator <IHat> hatIterator = hats. listIterator ();
While (hatIterator. hasNext ()){
IHat hat = hatIterator. next ();
If (hat. hasEarFlaps ()){
HatIterator. remove ();
HatIterator. add (sombrero );
}
}
Use ListIterator to call the remove and add methods, which can be replaced by calling only one set method:
IHat sombrero = new Sombrero ();
ListIterator <IHat> hatIterator = hats. listIterator ();
While (hatIterator. hasNext ()){
IHat hat = hatIterator. next ();
If (hat. hasEarFlaps ()){
HatIterator. set (sombrero); // set instead of remove and add
}
}
Use the stream method in Java 8
In Java 8, developers can convert a collection to stream and filter the stream based on some conditions. This example describes how stream api filters hats and avoids ConcurrentModificationException. Hats = hats. stream (). filter (hat->! Hat. hasEarFlaps ()))
. Collect (Collectors. toCollection (ArrayList: new ));
The Collectors. toCollection method creates a new ArrayList, which stores the filtered hats values. If the filter condition filters out a large number of entries, a large ArrayList is generated. Therefore, use it with caution.
Use the List. removeIf method in Java 8
You can use another more concise and clear method in Java 8 -- removeIf method:
Hats. removeIf (IHat: hasEarFlaps );
At the underlying layer, it uses Iterator. remove to complete this operation.
Use a special set
If you decide to use CopyOnWriteArrayList instead of ArrayList at the beginning, no problem will occur. Because CopyOnWriteArrayList provides a modification method such as set, add, remove), it does not change the original set array, but creates a new version. This allows you to traverse the original version set and modify it at the same time, so as not to throw a ConcurrentModificationException. The disadvantages of this set are also obvious-a new set is generated for each modification.
There are other sets suitable for different scenarios, such as CopyOnWriteSet and ConcurrentHashMap.
Another error that may occur when a set is modified concurrently is that a stream is created from a collection and the back-end collection is modified when the stream is traversed. The general rule for stream is to avoid modifying the back-end collection when querying stream. The following example shows how to process stream correctly:
List <IHat> filteredHats = hats. stream (). peek (hat-> {
If (hat. hasEarFlaps ()){
Hats. remove (hat );
}
}). Collect (Collectors. toCollection (ArrayList: new ));
The peek method collects all the elements and performs the specified action on each element. Here, the action is to try to delete data from a basic list, which is obviously incorrect. To avoid such operations, you can try some methods described above.
4. Default
Sometimes, for better collaboration, Code provided by a standard library or a third party must comply with common dependency standards. For example, you must abide by the common conventions of hashCode and equals to ensure that a series of collection classes in the Java Collection framework and other classes using the hashCode and equals methods can work normally. Non-compliance does not produce exceptions or corrupt code compilation errors; it is very sinister because it may change application behavior at any time without any danger.
The error code may sneak into the production environment, causing a lot of adverse effects. This includes poor UI experience, incorrect data reports, poor application performance, data loss, or more. Fortunately, these catastrophic errors won't happen frequently. The hashCode and equals conventions have been mentioned before. They may occur in the following scenarios: A set depends on hashing or comparing objects, just like HashMap and HashSet. In short, this Convention has two principles:
-
If the two objects are the same, the hash code must be the same.
-
If two objects have the same hash code, they may be equal or not equal.
If you attempt to retrieve data from a hashmap, the first criterion of the conventions will be broken. The second criterion means that objects with the same hash code are not necessarily equal.
The following describes the consequences of undermining the first criterion:
Public static class Boat {
Private String name;
Boat (String name ){
This. name = name;
}
@ Override
Public boolean equals (Object o ){
If (this = o) return true;
If (o = null | getClass ()! = O. getClass () return false;
Boat boat = (Boat) o;
Return! (Name! = Null? ! Name. equals (boat. name): boat. name! = Null );
}
@ Override
Public int hashCode (){
Return (int) (Math. random () * 5000 );
}
}
As you can see, the Boat class overrides the equals and hashCode methods. However, it breaks the Convention because hashCode returns a random value for the same object in each call. The following code may not find a boat named Enterprise in hashset, although we actually added this type of boat in advance:
Public static void main (String [] args ){
Set <Boat> boats = new HashSet <> ();
Boats. add (new Boat ("Enterprise "));
System. out. printf ("We have a boat named 'enter': % B/n", boats. contains (new Boat ("Enterprise ")));
}
Another example of the Convention is the finalize method. Here is a reference to the official Java documentation on its function description:
The General Convention of finalize is: when the JavaTM Virtual Machine determines that no thread can access the specified object in any way, this method will be called, and then this object can only be terminated in some other way) an object or a class is the final result of a behavior. The finalize method has multiple functions, including re-enabling the object to be available to other threads. However, the main purpose of finalize is to clear the object before it can be unundone. For example, the finalize method of the input/output connection object can execute an explicit I/O transaction to interrupt the connection before the object is permanently discarded.
You can decide to use the finalize method in a file processor to release resources, but this usage is terrible. Because it is called during garbage collection, and the GC time is not determined, The finalize call time cannot be guaranteed.
5. Use the original type instead of parameterized
According to the description in the Java document, the original type is either non-parameterized, or non-static member of the class R and non-inherited R parent class or parent interface. Before Java generics are introduced, there is no replacement type for the original type. Java has supported generic programming since version 1.5, which is undoubtedly an important feature improvement. However, due to backward compatibility, there is a trap that may damage the entire type system. Focus on the following example:
List listOfNumbers = new ArrayList ();
ListOfNumbers. add (10 );
ListOfNumbers. add ("Twenty ");
ListOfNumbers. forEach (n-> System. out. println (int) n * 2 ));
A list composed of numbers is defined as the original ArrayList. Because it does not specify a type parameter, you can add any object to it. However, the last line maps the contained elements to the int type and multiplied by 2 to print the data after doubling to the standard output.
This Code does not cause errors during compilation, but once it is run, it throws a runtime error because it attempts to map the character type to an integer. Obviously, if necessary information is hidden, the type system cannot help write security code.
To solve this problem, you need to specify a specific type for the objects stored in the Set:
List <Integer> listOfNumbers = new ArrayList <> ();
ListOfNumbers. add (10 );
ListOfNumbers. add ("Twenty ");
ListOfNumbers. forEach (n-> System. out. println (int) n * 2 ));
The only difference from the previous code is the line that defines the set:
List <Integer> listOfNumbers = new ArrayList <> ();
The modified code compilation cannot be passed because it attempts to add a string to the set that only expects to store the integer. The compiler displays an error message and points to the line that tries to add the Twenty character to the list. Parameterized generic type is a good idea. In this way, the compiler can check all possible types, thus greatly reducing the chance of running exceptions caused by inconsistent types.