Java development programming specification (Ali Baba edition): 5 collection process

Here Insert Picture Description

  1. [Mandatory] treatment on hashCode and equals, the following rules:

     1) As long as rewriting equals, it is necessary to rewrite hashCode.

     2) it is not stored because the Set duplicate objects, is determined by their hashCode and equals, so the object is stored Set must override these two methods.

     3) If the custom objects as Map keys, you must rewrite the hashCode and equals.

说明:String 重写了 hashCode 和 equals 方法,所以我们可以非常愉快地使用 String 对象作为 key 来使用。

  1. [Mandatory] subList results ArrayList of ArrayList can not turn into a strong, otherwise it will throw a ClassCastException that java.util.RandomAccessSubList can not be cast to java.util.ArrayList.

说明:subList 返回的是 ArrayList 的内部类 SubList,并不是 ArrayList 而是 ArrayList 的一个视图,对于 SubList 子列表的所有操作最终会反映到原列表上。

  1. [Mandatory] in subList scene, pay attention to the height of the original collection of elements to add or remove, will lead to traverse the sub-lists, add, delete produce ConcurrentModificationException exception.

  2. [Force] using the method set switch array, must be set toArray (T [] array), is passed in exactly the same type of array size is list.size ().

说明:使用 toArray 带参方法,入参分配的数组空间不够大时,toArray 方法内部将重新分配内存空间,并返回新数组地址;如果数组元素个数大于实际所需,下标为[ list.size() ] 的数组元素将被置为 null,其它数组元素保持原值,因此最好将方法入参数组大小定义与集合元素个数一致。

Positive examples:

List<String> list = new ArrayList<String>(2); 
list.add("guan"); 
list.add("bao"); 
String[] array = new String[list.size()]; 
array = list.toArray(array);

反例:直接使用 toArray 无参方法存在问题,此方法返回值只能是 Object[]类,若强转其它 类型数组将出现 ClassCastException 错误。

  1. [Force] using tools Arrays.asList () array into a set of time, which can not be used to modify a set of related methods, it add / remove / clear method throws an UnsupportedOperationException.

说明:asList 的返回对象是一个 Arrays 内部类,并没有实现集合的修改方法。Arrays.asList 体现的是适配器模式,只是转换接口,后台的数据仍是数组。

String[] str = new String[] { "you", "wu" }; 
List list = Arrays.asList(str); 
// 第一种情况:list.add("yangguanbao"); 运行时异常。 
// 第二种情况:str[0] = "gujin"; 那么 list.get(0)也会随之修改。 
  1. [Mandatory] generic wildcard <? Extends T> to receive the data returned, the wording of this generic collections can not use the add method, and <? Super T> get method can not be used as an interface call assignment when error-prone.

说明:扩展说一下 PECS(Producer Extends Consumer Super)原则:第一、频繁往外读取内容的,适合用<? extends T>。第二、经常往里插入的,适合用<? super T>。

  1. [Mandatory] Do not make the element remove / add operations in the foreach loop. remove elements, use Iterator way, if concurrent operations, the need for Iterator object locking.
    Positive examples:
List<String> list = new ArrayList<>(); 
list.add("1"); list.add("2"); 
Iterator<String> iterator = list.iterator(); 
while (iterator.hasNext()) { 
    String item = iterator.next(); 
    if (删除元素的条件) { 
        iterator.remove(); 
    } 
}

Counterexample:

for (String item : list) { if ("1".equals(item)) { list.remove(item); } }

说明:以上代码的执行结果肯定会出乎大家的意料,那么试一下把“1”换成“2”,会是同样的 结果吗?

  1. [Mandatory] in JDK7 version and above, Comparator implementation class to meet the following three conditions, or Arrays.sort, Collections.sort will be reported IllegalArgumentException.
    Description: the following three conditions
         1) x, y, and a comparison result comparison result y, x is the opposite.
         2) x> y, y> z, then x> z.
         3) x = y, then x, z comparison result and y, z the same comparison result.

Anti Example: The following example does not handle equal, an exception may occur in actual use:

new Comparator<Student>() { 
@Override 
public int compare(Student o1, Student o2) { 
    return o1.getId() > o2.getId() ? 1 : -1; 
    } 
}; 
  1. [Recommended] when a generic set of definitions, JDK7 and above, use diamond syntax or full omitted.

说明:菱形泛型,即 diamond,直接使用<>来指代前边已经指定的类型。

Positive examples:

// <> diamond 方式 
HashMap<String, String> userCache = new HashMap<>(16); 
// 全省略方式 
ArrayList<User> users = new ArrayList(10);
  1. [Recommended] when a collection is initialized, the initial value of a specified set size.

说明:HashMap 使用 HashMap(int initialCapacity) 初始化。
正例:initialCapacity = (需要存储的元素个数 / 负载因子) + 1。注意负载因子(即 loader factor)默认为 0.75,如果暂时无法确定初始值大小,请设置为 16(即默认值)。
反例:HashMap 需要放置 1024 个元素,由于没有设置容量初始大小,随着元素不断增加,容 量 7 次被迫扩大,resize 需要重建 hash 表,严重影响性能。

  1. [Recommended] Use entrySet traverse Map collection of classes KV, rather than keySet way to traverse.

说明:keySet 其实是遍历了 2 次,一次是转为 Iterator 对象,另一次是从 hashMap 中取出 key 所对应的 value。而 entrySet 只是遍历了一次就把 key 和 value 都放到了 entry 中,效 率更高。如果是 JDK8,使用 Map.foreach 方法。
正例:values()返回的是 V 值集合,是一个 list 集合对象;keySet()返回的是 K 值集合,是一个 Set 集合对象;entrySet()返回的是 K-V 值组合集合。

  1. [Recommended] Height Map attention class set K / V can store null value, the following form:
Collections Key Value Super Explanation
Hashtable Does not permit null Does not permit null Dictionary Thread Safety
ConcurrentHashMap Does not permit null Does not permit null AbstractMap Lock segmentation technique (JDK8: CAS)
TreeMap Does not permit null Be null AbstractMap Thread safe
HashMap Be null Be null AbstractMap Thread safe

反例: 由于 HashMap 的干扰,很多人认为 ConcurrentHashMap 是可以置入 null 值,而事实上, 存储 null 值时会抛出 NPE 异常。

  1. [Reference] rational use of orderliness (sort) and good stability of the set (order), to avoid the negative effects of the disorder collections (unsort) and instability (unorder) brings.

说明:有序性是指遍历的结果是按某种比较规则依次排列的。稳定性指集合每次遍历的元素次序是一定的。如:ArrayList 是 order/unsort;HashMap 是 unorder/unsort;TreeSet 是order/sort。

  1. [Reference] with a unique characteristic Set element, can quickly go to a set of re-operation, to avoid the use of List contains traversing method, compared to retry.
Published 74 original articles · won praise 180 · views 30000 +

Guess you like

Origin blog.csdn.net/Fdog_/article/details/104897606