Collection processing
1. [Mandatory] Regarding the processing of hashCode and equals, follow the following rules:
1) As long as equals is rewritten, hashCode must be rewritten.
2) Because Set stores unique objects and is judged based on hashCode and equals, the
objects stored in Set must override these two methods.
3) If a custom object is used as a Map key, hashCode and equals must be overridden.
Positive example: String overrides the hashCode and equals methods, so we can happily use String objects as keys.
#2. [Mandatory] The subList result of ArrayList cannot be forcibly converted into ArrayList, otherwise ClassCastException exception will be thrown: java . util . RandomAccessSubList cannot be cast to java . util . ArrayList ;
Explanation: subList returns the internal class SubList of ArrayList, not ArrayList, but a view of ArrayList, for All operations on SubList will eventually be reflected on the original list.
3. [Mandatory] In the subList scenario, pay great attention to modifying the number of elements in the original collection, which will lead to traversal and increase of the sublist Adding and deleting will generate ConcurrentModificationException.
4. [Mandatory] To use the method of converting a collection to an array, you must use the toArray(T[] array) of the collection, and the type passed in is completely The same array, the size is list. size().
Counter example: There is a problem with using toArray directly without parameters. The return value of this method can only be the Object[] class. If you force-cast other type arrays, a ClassCastException will occur. mistake.
Positive example:
List<String> list = new ArrayList<String>(2); list.add("guan"); list.add("bao"); String[] array = new String[list.size()]; array = list.toArray(array);
Explanation: Use the toArray parameter method, and when the array space allocated for the input parameters is not large enough, toArray The memory space will be reallocated internally in the method and the new array address will be returned; if the array element is larger than actually required, the array element with the subscript [list . size()] will be set to null. Other array elements retain their original values, so it is best to define the size of the method input parameter group to be consistent with the number of elements in the collection.
5. [Mandatory] When using the tool class Arrays. asList() to convert an array into a collection, you cannot use its methods related to modifying the collection , its add/remove/clear methods will throw UnsupportedOperationException.
Note: The return object of asList is an Arrays internal class and does not implement the collection modification method. Arrays. asList embodies the adapter mode, which only converts the interface, and the background data is still an array.
String[] str = new String[] { "a", "b" }; List list = Arrays.asList(str);
The first situation: list.add("c"); Runtime exception.
The second case: str[0]= "gujin"; then list.get(0) will also be modified accordingly.
6. [Mandatory] Use the generic wildcard character <? extends T > to receive the returned data. The add method cannot be used for generic collections written in this way. .
Description: After packing the apples, an <? extends Fruits > object is returned. This object cannot add any fruits, including apples.
7. [Mandatory] Do not perform remove/add operations on elements in a foreach loop. Please use the Iterator
method to remove elements. If you operate concurrently, you need to lock the Iterator object.
Counterexample:
List<String> a = new ArrayList<String>(); a.add("1"); a.add("2"); for (String temp : a) { if("1".equals(temp)){ a.remove(temp); } }
Explanation: The execution result of the above code will definitely be beyond everyone’s expectations, so try replacing “1” If it becomes "2", will it have the same result?
Positive example:
Iterator<String> it = a.iterator(); while(it.hasNext()){ String temp = it.next(); if(删除元素的条件){ it.remove(); } }
8. [Mandatory] In JDK version 7 or above, Comparator must satisfy reflexivity, transitivity, and symmetry, otherwise Arrays. sort, Collections. sort will report an IllegalArgumentException exception.
Explanation:
1) Reflexivity: The comparison result of x and y is opposite to the comparison result of y and x.
2) Transitivity: x > y, y > z, then x > z.
3) Symmetry: x = y, then the comparison results of x and z are the same as the comparison results of y and z.
Counterexample: The following example does not handle equality situations, and exceptions may occur in actual use:
new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getId() > o2.getId() ? 1 : -1; } }
9. [Recommendation] When initializing a collection, try to specify the collection Initial value size.
Note: Try to use ArrayList(int initialCapacity) to initialize ArrayList.
10. [Recommended] Use entrySet to traverse the Map class collection KV instead of keySet.
Explanation: The keySet is actually traversed twice, one is to convert it to an Iterator object, and the other is to retrieve the value corresponding to the key from the hashMap. The entrySet only traverses once and puts both the key and value into the entry, which is more efficient. In case of JDK 8, use Map . foreach method. Positive example: values() returns a V value set, which is a list collection object; keySet() returns a K value set, which is a Set collection object; entrySet() What is returned is a collection of K - V value combinations. 11. [Recommended] Pay close attention to whether the Map class collection K / V can store null values, as shown in the following table: Counter example: Due to the interference of HashMap, many people think that ConcurrentHashMap can place null values. Note that an NPE exception will be thrown when storing null values. 12. [Reference] Make good use of the order (sort) and stability (order) of the set and avoid the disorder of the set (unsort) And the negative impact caused by instability (unorder). Explanation: Stability means that the order of elements in the collection is certain each time it is traversed. Orderliness means that the traversal results are arranged in order according to certain comparison rules. For example: ArrayList is order / unsort; HashMap is unorder / unsort; TreeSet is order / sort. #13. [Reference] Using the unique characteristics of the Set element, you can quickly deduplicate a collection and avoid using the contains method of List. Traverse, compare, and remove duplicate operations.