Java集合---Array类源码解析
Java集合---Array类源码解析 ---转自:牛奶、不加糖
一、Arrays.sort()数组排序
Java Arrays中提供了对所有类型的排序。其中主要分为Primitive(8种基本类型)和Object两大类。
基本类型:采用调优的快速排序;
对象类型:采用改进的归并排序。
1、对于基本类型源码分析如下(以int[]为例):
Java对Primitive(int,float等原型数据)数组采用快速排序,对Object对象数组采用归并排序。对这一区别,sun在<<The Java Tutorial>>中做出的解释如下:
The sort operation uses a slightly optimized merge sort algorithm that is fast and stable:
* Fast: It is guaranteed to run in n log(n) time and runs substantially faster on nearly sorted lists. Empirical tests showed it to be as fast as a highly optimized quicksort. A quicksort is generally considered to be faster than a merge sort but isn't stable and doesn't guarantee n log(n) performance.
* Stable: It doesn't reorder equal elements. This is important if you sort the same list repeatedly on different attributes. If a user of a mail program sorts the inbox by mailing date and then sorts it by sender, the user naturally expects that the now-contiguous list of messages from a given sender will (still) be sorted by mailing date. This is guaranteed only if the second sort was stable.
也就是说,优化的归并排序既快速(nlog(n))又稳定。
对于对象的排序,稳定性很重要。比如成绩单,一开始可能是按人员的学号顺序排好了的,现在让我们用成绩排,那么你应该保证,本来张三在李四前面,即使他们成绩相同,张三不能跑到李四的后面去。
而快速排序是不稳定的,而且最坏情况下的时间复杂度是O(n^2)。
另外,对象数组中保存的只是对象的引用,这样多次移位并不会造成额外的开销,但是,对象数组对比较次数一般比较敏感,有可能对象的比较比单纯数的比较开销大很多。归并排序在这方面比快速排序做得更好,这也是选择它作为对象排序的一个重要原因之一。
排序优化:实现中快排和归并都采用递归方式,而在递归的底层,也就是待排序的数组长度小于7时,直接使用冒泡排序,而不再递归下去。
分析:长度为6的数组冒泡排序总比较次数最多也就1+2+3+4+5+6=21次,最好情况下只有6次比较。而快排或归并涉及到递归调用等的开销,其时间效率在n较小时劣势就凸显了,因此这里采用了冒泡排序,这也是对快速排序极重要的优化。
源码中的快速排序,主要做了以下几个方面的优化:
1)当待排序的数组中的元素个数较少时,源码中的阀值为7,采用的是插入排序。尽管插入排序的时间复杂度为0(n^2),但是当数组元素较少时,插入排序优于快速排序,因为这时快速排序的递归操作影响性能。
2)较好的选择了划分元(基准元素)。能够将数组分成大致两个相等的部分,避免出现最坏的情况。例如当数组有序的的情况下,选择第一个元素作为划分元,将使得算法的时间复杂度达到O(n^2).
源码中选择划分元的方法:
当数组大小为 size=7 时 ,取数组中间元素作为划分元。int n=m>>1;(此方法值得借鉴)
当数组大小 7<size<=40时,取首、中、末三个元素中间大小的元素作为划分元。
当数组大小 size>40 时 ,从待排数组中较均匀的选择9个元素,选出一个伪中数做为划分元。
3)根据划分元 v ,形成不变式 v* (<v)* (>v)* v*
普通的快速排序算法,经过一次划分后,将划分元排到素组较中间的位置,左边的元素小于划分元,右边的元素大于划分元,而没有将与划分元相等的元素放在其附近,这一点,在Arrays.sort()中得到了较大的优化。
举例:15、93、15、41、6、15、22、7、15、20
因 7<size<=40,所以在15、6、和20 中选择v = 15 作为划分元。
经过一次换分后: 15、15、7、6、41、20、22、93、15、15. 与划分元相等的元素都移到了素组的两边。
接下来将与划分元相等的元素移到数组中间来,形成:7、6、15、15、15、15、41、20、22、93.
最后递归对两个区间进行排序[7、6]和[41、20、22、93].
部分源代码(一)如下:

1 package com.util;
2
3 public class ArraysPrimitive {
4 private ArraysPrimitive() {}
5
6 /**
7 * 对指定的 int 型数组按数字升序进行排序。
8 */
9 public static void sort(int[] a) {
10 sort1(a, 0, a.length);
11 }
12
13 /**
14 * 对指定 int 型数组的指定范围按数字升序进行排序。
15 */
16 public static void sort(int[] a, int fromIndex, int toIndex) {
17 rangeCheck(a.length, fromIndex, toIndex);
18 sort1(a, fromIndex, toIndex - fromIndex);
19 }
20
21 private static void sort1(int x[], int off, int len) {
22 /*
23 * 当待排序的数组中的元素个数小于 7 时,采用插入排序 。
24 *
25 * 尽管插入排序的时间复杂度为O(n^2),但是当数组元素较少时, 插入排序优于快速排序,因为这时快速排序的递归操作影响性能。
26 */
27 if (len < 7) {
28 for (int i = off; i < len + off; i++)
29 for (int j = i; j > off && x[j - 1] > x[j]; j--)
30 swap(x, j, j - 1);
31 return;
32 }
33 /*
34 * 当待排序的数组中的元素个数大于 或等于7 时,采用快速排序 。
35 *
36 * Choose a partition element, v
37 * 选取一个划分元,V
38 *
39 * 较好的选择了划分元(基准元素)。能够将数组分成大致两个相等的部分,避免出现最坏的情况。例如当数组有序的的情况下,
40 * 选择第一个元素作为划分元,将使得算法的时间复杂度达到O(n^2).
41 */
42 // 当数组大小为size=7时 ,取数组中间元素作为划分元。
43 int m = off + (len >> 1);
44 // 当数组大小 7<size<=40时,取首、中、末 三个元素中间大小的元素作为划分元。
45 if (len > 7) {
46 int l = off;
47 int n = off + len - 1;
48 /*
49 * 当数组大小 size>40 时 ,从待排数组中较均匀的选择9个元素,
50 * 选出一个伪中数做为划分元。
51 */
52 if (len > 40) {
53 int s = len / 8;
54 l = med3(x, l, l + s, l + 2 * s);
55 m = med3(x, m - s, m, m + s);
56 n = med3(x, n - 2 * s, n - s, n);
57 }
58 // 取出中间大小的元素的位置。
59 m = med3(x, l, m, n); // Mid-size, med of 3
60 }
61
62 //得到划分元V
63 int v = x[m];
64
65 // Establish Invariant: v* (<v)* (>v)* v*
66 int a = off, b = a, c = off + len - 1, d = c;
67 while (true) {
68 while (b <= c && x[b] <= v) {
69 if (x[b] == v)
70 swap(x, a++, b);
71 b++;
72 }
73 while (c >= b && x[c] >= v) {
74 if (x[c] == v)
75 swap(x, c, d--);
76 c--;
77 }
78 if (b > c)
79 break;
80 swap(x, b++, c--);
81 }
82 // Swap partition elements back to middle
83 int s, n = off + len;
84 s = Math.min(a - off, b - a);
85 vecswap(x, off, b - s, s);
86 s = Math.min(d - c, n - d - 1);
87 vecswap(x, b, n - s, s);
88 // Recursively sort non-partition-elements
89 if ((s = b - a) > 1)
90 sort1(x, off, s);
91 if ((s = d - c) > 1)
92 sort1(x, n - s, s);
93 }
94
95 /**
96 * Swaps x[a] with x[b].
97 */
98 private static void swap(int x[], int a, int b) {
99 int t = x[a];
100 x[a] = x[b];
101 x[b] = t;
102 }
103
104 /**
105 * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)].
106 */
107 private static void vecswap(int x[], int a, int b, int n) {
108 for (int i=0; i<n; i++, a++, b++)
109 swap(x, a, b);
110 }
111
112 /**
113 * Returns the index of the median of the three indexed integers.
114 */
115 private static int med3(int x[], int a, int b, int c) {
116 return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a)
117 : (x[b] > x[c] ? b : x[a] > x[c] ? c : a));
118 }
119
120 /**
121 * Check that fromIndex and toIndex are in range, and throw an
122 * appropriate exception if they aren't.
123 */
124 private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
125 if (fromIndex > toIndex)
126 throw new IllegalArgumentException("fromIndex(" + fromIndex
127 + ") > toIndex(" + toIndex + ")");
128 if (fromIndex < 0)
129 throw new ArrayIndexOutOfBoundsException(fromIndex);
130 if (toIndex > arrayLen)
131 throw new ArrayIndexOutOfBoundsException(toIndex);
132 }
133 }

测试代码如下:

1 package com.test;
2
3 import com.util.ArraysPrimitive;
4
5 public class ArraysTest {
6 public static void main(String[] args) {
7 int [] a={15,93,15,41,6,15,22,7,15,20};
8 ArraysPrimitive.sort(a);
9 for(int i=0;i<a.length;i++){
10 System.out.print(a[i]+",");
11 }
12 //结果:6,7,15,15,15,15,20,22,41,93,
13 }
14 }

2、对于Object类型源码分析如下:
部分源代码(二)如下:
package com.util;
import java.lang.reflect.Array;
public class ArraysObject {
private static final int INSERTIONSORT_THRESHOLD = 7;
private ArraysObject() {}
public static void sort(Object[] a) {
//java.lang.Object.clone(),理解深表复制和浅表复制
Object[] aux = (Object[]) a.clone();
mergeSort(aux, a, 0, a.length, 0);
}
public static void sort(Object[] a, int fromIndex, int toIndex) {
rangeCheck(a.length, fromIndex, toIndex);
Object[] aux = copyOfRange(a, fromIndex, toIndex);
mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
}
/**
* Src is the source array that starts at index 0
* Dest is the (possibly larger) array destination with a possible offset
* low is the index in dest to start sorting
* high is the end index in dest to end sorting
* off is the offset to generate corresponding low, high in src
*/
private static void mergeSort(Object[] src, Object[] dest, int low,
int high, int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i = low; i < high; i++)
for (int j = i; j > low &&
((Comparable) dest[j - 1]).compareTo(dest[j]) > 0; j--)
swap(dest, j, j - 1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
/*
* >>>:无符号右移运算符
* expression1 >>> expresion2:expression1的各个位向右移expression2
* 指定的位数。右移后左边空出的位数用0来填充。移出右边的位被丢弃。
* 例如:-14>>>2; 结果为:1073741820
*/
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable) src[mid - 1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for (int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid
&& ((Comparable) src[p]).compareTo(src[q]) <= 0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
}
/**
* Check that fromIndex and toIndex are in range, and throw an appropriate
* exception if they aren't.
*/
private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex
+ ") > toIndex(" + toIndex + ")");
if (fromIndex < 0)
throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > arrayLen)
throw new ArrayIndexOutOfBoundsException(toIndex);
}
public static <T> T[] copyOfRange(T[] original, int from, int to) {
return copyOfRange(original, from, to, (Class<T[]>) original.getClass());
}
public static <T, U> T[] copyOfRange(U[] original, int from, int to,
Class<? extends T[]> newType) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
T[] copy = ((Object) newType == (Object) Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
/**
* Swaps x[a] with x[b].
*/
private static void swap(Object[] x, int a, int b) {
Object t = x[a];
x[a] = x[b];
x[b] = t;
}
}
测试代码如下:
package com.test;
import com.util.ArraysObject;
public class ArraysObjectSortTest {
public static void main(String[] args) {
Student stu1=new Student(1001,100.0F);
Student stu2=new Student(1002,90.0F);
Student stu3=new Student(1003,90.0F);
Student stu4=new Student(1004,95.0F);
Student[] stus={stu1,stu2,stu3,stu4};
//Arrays.sort(stus);
ArraysObject.sort(stus);
for(int i=0;i<stus.length;i++){
System.out.println(stus[i].getId()+" : "+stus[i].getScore());
}
/* 1002 : 90.0
* 1003 : 90.0
* 1004 : 95.0
* 1001 : 100.0
*/
}
}
class Student implements Comparable<Student>{
private int id; //学号
private float score; //成绩
public Student(){}
public Student(int id,float score){
this.id=id;
this.score=score;
}
@Override
public int compareTo(Student s) {
return (int)(this.score-s.getScore());
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
辅助理解代码:
package com.lang;
public final class System {
//System 类不能被实例化。
private System() {}
//在 System 类提供的设施中,有标准输入、标准输出和错误输出流;对外部定义的属性
//和环境变量的访问;加载文件和库的方法;还有快速复制数组的一部分的实用方法。
/**
* src and dest都必须是同类型或者可以进行转换类型的数组.
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
*/
public static native void arraycopy(Object src, int srcPos, Object dest,
int destPos, int length);
}
package com.lang.reflect;
public final class Array {
private Array() {}
//创建一个具有指定的组件类型和维度的新数组。
public static Object newInstance(Class<?> componentType, int length)
throws NegativeArraySizeException {
return newArray(componentType, length);
}
private static native Object newArray(Class componentType, int length)
throws NegativeArraySizeException;
}
二、Arrays.asList
慎用ArrayList的contains方法,使用HashSet的contains方法代替
在启动一个应用的时候,发现其中有一处数据加载要数分钟,刚开始以为是需要load的数据比较多的缘故,查了一下数据库有6条左右,但是单独写了一个数据读取的方法,将这6万多条全部读过来,却只需要不到10秒钟,就觉得这里面肯定有问题,于是仔细看其中的逻辑,其中有一段数据去重的逻辑,就是记录中存在某几个字段相同的,就认为是重复数据,就需要将重复数据给过滤掉。这里就用到了一个List来存放这几个字段所组成的主键,如果发现相同的就不处理,代码无非就是下面这样:
1 List<string> uniqueKeyList = new ArrayList<string>();
2 //......
3 if (uniqueKeyList.contains(uniqueKey)) {
4 continue;
}
根据键去查找是不是已经存在了,来判断是否重复数据。经过分析,这一块耗费了非常多的时候,于是就去查看ArrayList的contains方法的源码,发现其最终会调用他本身的indexOf方法:

7public int indexOf(Object elem) {
8 if (elem == null) {
9 for (int i = 0; i < size; i++)
10 if (elementData[i]==null)
11 return i;
12 } else {
13 for (int i = 0; i < size; i++)
14 if (elem.equals(elementData[i]))
15 return i;
16 }
17 return -1;
18 }

原来在这里他做的是遍历整个list进行查找,最多可能对一个键的查找会达到6万多次,也就是会扫描整个List,验怪会这么慢了。
于是将原来的List替换为Set:
Set<string> uniqueKeySet = new HashSet<string>();
//......
if (uniqueKeySet.contains(uniqueKey)) {
continue;
}
速度一下就上去了,在去重这一块最多花费了一秒钟,为什么HashSet的速度一下就上去了,那是因为其内部使用的是Hashtable,这是HashSet的contains的源码:
public boolean contains(Object o) {
return map.containsKey(o);
}
关于UnsupportedOperationException异常
在使用Arrays.asList()后调用add,remove这些method时出现java.lang.UnsupportedOperationException异常。这是由于Arrays.asList() 返回java.util.Arrays$ArrayList, 而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,remove,add等method在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。ArrayList override这些method来对list进行操作,但是Arrays$ArrayList没有override remove(),add()等,所以throw UnsupportedOperationException。
Java集合---Array类源码解析的更多相关文章
- Java集合---Arrays类源码解析
一.Arrays.sort()数组排序 Java Arrays中提供了对所有类型的排序.其中主要分为Primitive(8种基本类型)和Object两大类. 基本类型:采用调优的快速排序: 对象类型: ...
- java.lang.Void类源码解析_java - JAVA
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 在一次源码查看ThreadGroup的时候,看到一段代码,为以下: /* * @throws NullPointerEx ...
- Java集合:LinkedList源码解析
Java集合---LinkedList源码解析 一.源码解析1. LinkedList类定义2.LinkedList数据结构原理3.私有属性4.构造方法5.元素添加add()及原理6.删除数据re ...
- 【Java集合】HashSet源码解析以及HashSet与HashMap的区别
HashSet 前言 HashSet是一个不可重复且元素无序的集合.内部使用HashMap实现. 我们可以从HashSet源码的类注释中获取到如下信息: 底层基于HashMap实现,所以迭代过程中不能 ...
- java.lang.Boolean 类源码解析
Boolean源码比较简单. public final class Boolean implements java.io.Serializable, Comparable<Boolean> ...
- java集合之HashMap源码解析
Map是java中的一种数据结构,围绕着Map接口,有一系列的实现类如Hashtable.HashMap.LinkedHashMap和TreeMap.而其中HashMap和Hashtable我们平常使 ...
- Java集合之LinkedList源码解析
LinkedList简介 LinkedList基于双向链表,即FIFO(先进先出)和FILO(先进后出)都是支持的,这样它可以作为堆栈,队列使用 继承AbstractSequentialList,该类 ...
- java集合之List源码解析
List是java重要的数据结构之一,我们经常接触到的有ArrayList.Vector和LinkedList三种,他们都继承来自java.util.Collection接口,类图如下 接下来,我们对 ...
- 死磕 java集合之PriorityBlockingQueue源码分析
问题 (1)PriorityBlockingQueue的实现方式? (2)PriorityBlockingQueue是否需要扩容? (3)PriorityBlockingQueue是怎么控制并发安全的 ...
随机推荐
- Caused by: java.sql.BatchUpdateException: Transaction error, need to rollback. errno:1205 Lock wait timeout exceeded; try restarting transaction
更新的时候报 Caused by: java.sql.BatchUpdateException: Transaction error, need to rollback. errno:1205 Loc ...
- 设计模式 “续”
观察者模式 再次申明,本文学习自 程杰 兄的 "大话设计模式" 根据书中的内容和自己的体会而来. 观察者模式也叫 发布.订阅模式,在这个模式里,一个目标物件管理所有依赖它的观察者物 ...
- Sublime Text 2 实用快捷键(Mac OS X)
打开/前往: ⌘T 前往文件 ⌘⌃P 前往项目 ⌘R 前往 method ⌘⇧P 命令提示 ⌃G 前往行 ⌃ ` python 控制台 ——————— 编辑: ⌘L 选择行 (重复按下将下一行加入选择 ...
- A=AUB
#include<stdio.h>#include<stdlib.h> #define LIST_MAX 10#define LIST_ADD 2 typedef struct ...
- Redis中持久化的两种方法详解
Redis提供了两种不同的持久化方法来将数据存储到硬盘里面.一种方法叫快照(snapshotting),它可以将存在于某一时刻的所有数据都写入硬盘里;另一种方法教只追加文件(append-only f ...
- Redis总结(四)Redis 的持久化
前面已经总结了Redis 的安装和使用今天讲下Redis 的持久化. redis跟memcached类似,都是内存数据库,不过redis支持数据持久化,也就是说redis可以将内存中的数据同步到磁盘来 ...
- cURL函数
PHP的cURL函数是通过libcurl库与服务器使用各种类型的协议进行连接和通信的,curl目前支持HTTP GET .HTTP POST .HTTPS认证.FTP上传.HTTP基于表单的上传.co ...
- SSAS动态添加分区(一)
一.动态分区的好处就不说了,随着时间的推移,不可能一个度量值组都放在一个分区中,处理速度非常慢,如何动态添加分区,如何动态处理分区,成为了很多新手BI工程师一个头痛的问题,废话不多说,分享一下我的经验 ...
- PHP正则表达式模式修饰符详解
PHP模式修饰符又叫模式修正符,是在正则表达式的定界符之外使用.主要用来调整正则表达式的解释,提扩展了正则表达式在匹配.替换等操作的某些功能,增强了正则的能力.但是有很多地方的解释都是错误的,也容易误 ...
- BZOJ2435——[Noi2011]道路修建
1.题意:给个树,边的权值=两边的点数差*此边的长度,求所有边的权值和 2.分析:真不想说啥了...dfs即可 #include <cmath> #include <cstdio&g ...