What are the best practices for the Java collection class framework?

  1. It is very important for performance to choose the collection type to be used correctly according to the application needs. For example, if you know that the size of the elements is fixed, it is more appropriate to use the Array type instead of the ArrayList type.

  2. Some collection types allow specifying initial capacity. Therefore, if we can estimate the number of elements stored, we can specify the initial capacity to avoid recalculating the hash value or expanding the capacity, etc.

  3. Always use generics for reasons of type safety, readability, and robustness. At the same time, using generics can also avoid ClassCastException at runtime.

  4. Using the immutable class provided by JDK as the key of the Map can avoid implementing the hashCode() and equals() methods for our own classes.

  5. Interface is better than implementation when programming

  6. If the underlying collection is actually empty, it returns a collection or array of length 0 instead of null.

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324610338&siteId=291194637