1.toMap实现
public static Map<Object, Object> toMap(Object[] array) { if (array == null) { return null; } //GOOD:提前预估Map的尺寸,减少内存的申请 final Map<Object, Object> map = new HashMap<Object, Object>((int) (array.length * 1.5)); for (int i = 0; i < array.length; i++) { Object object = array[i]; if (object instanceof Map.Entry<?, ?>) { Map.Entry<?,?> entry = (Map.Entry<?,?>) object; map.put(entry.getKey(), entry.getValue()); } else if (object instanceof Object[]) { Object[] entry = (Object[]) object; if (entry.length < 2) { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', has a length less than 2"); } map.put(entry[0], entry[1]); } else { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', is neither of type Map.Entry nor an Array"); } } return map; }
亮点:预估Map尺寸,减少了内存操作;
2.removeAll实现
/** * Removes multiple array elements specified by index. * @param array source * @param indices to remove, WILL BE SORTED--so only clones of user-owned arrays! * @return new array of same type minus elements specified by unique values of {@code indices} * @since 3.0.1 *GOOD:int... indices 可变参数,最终是一个数组形式在函数中出现 删除元素时,需要倒序删除元素 否则会造成删除index值不对应元素值; *TOKNOW:经典算法 需要研究一下 */ private static Object removeAll(Object array, int... indices) { int length = getLength(array); int diff = 0; //查找索引值中不重复索引值的个数 if (isNotEmpty(indices)) { Arrays.sort(indices); int i = indices.length; int prevIndex = length; while (--i >= 0) { int index = indices[i]; if (index < 0 || index >= length) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); } if (index >= prevIndex) { continue; } diff++; prevIndex = index; } } Object result = Array.newInstance(array.getClass().getComponentType(), length - diff); //倒序操作 除去删除元素以外 分段复制到result中 if (diff < length) { int end = length; int dest = length - diff; for (int i = indices.length - 1; i >= 0; i--) { int index = indices[i]; if (end - index > 1) { int cp = end - index - 1; dest -= cp; System.arraycopy(array, index + 1, result, dest, cp); } end = index; } if (end > 0) { System.arraycopy(array, 0, result, 0, end); } } // for循环实现 // int index=indices.length-1; // for(int j=length-diff-1,i=length-1;i>=0;i--){ // if(i==indices[index]){ // Arrays.set(result,j--,array[i]); // index--; // }else if(i<indices[index]){ // index--; // }else{ // Arrays.set(result,j--,array[i]); // } // } return result; }
亮点:
0.先对索引值进行排序,查找不重复索引值的个数;
1.使用System.arraycopy进行数据分段复制,而不是使用for循环操作,大部分情况下效率比for循环高 (http://suddenlychen.iteye.com/blog/835423)
2.使用倒序删除元素;