1 arrays.aslist转换基本类型数组的坑
1.1 错误还原
在实际的业务开发中,我们通常会进行数组转list的操作,通常我们会使用arrays.aslist来进行转换
但是在转换基本类型的数组的时候,却出现转换的结果和我们想象的不一致。
看代码:
int[] arr = {1, 2, 3};
list list = arrays.aslist(arr);
system.out.println(list.size());
实际上,我们想要转成的list应该是有三个对象而现在只有一个
public static list aslist(t... a) {
return new arraylist<>(a);
}
可以观察到 aslist方法 接收的是一个泛型t类型的参数,t继承object对象
所以通过断点我们可以看到把 int数组 整体作为一个对象,返回了一个 list<int[]>

1.2 解决方案
方案一:java8以上,利用arrays.stream(arr).boxed()将装箱为integer数组
list collect = arrays.stream(arr).boxed().collect(collectors.tolist()); system.out.println(collect.size()); system.out.println(collect.get(0).getclass()); // 3 // class java.lang.integer
方案二:声明数组的时候,声明类型改为包装类型
integer[] integerarr = {1, 2, 3};
list integerlist = arrays.aslist(integerarr);
system.out.println(integerlist.size()); system.out.println(integerlist.get(0).getclass());
// 3
// class java.lang.integer
2 arrays.aslist返回的list不支持增删操作
我们将数组对象转成list数据结构之后,竟然不能进行增删操作了
private static void aslistadd(){
string[] arr = {"1", "2", "3"};
list<string> strings = new arraylist<>(arrays.aslist(arr));
arr[2] = "4";
system.out.println(strings.tostring());
iterator<string> iterator = strings.iterator();
while (iterator.hasnext()){
if ("4".equals(iterator.next())){
iterator.remove();
}
}
strings.foreach(val ->{
strings.remove("4");
strings.add("3");
});
system.out.println(arrays.aslist(arr).tostring());
}
[1, 2, 4]
exception in thread "main" java.lang.unsupportedoperationexception at java.util.abstractlist.remove(abstractlist.java:161) at java.util.abstractlist$itr.remove(abstractlist.java:374) at java.util.abstractcollection.remove(abstractcollection.java:293) at javabase.list.aslisttest.lambda$aslistadd$0(aslisttest.java:47) at java.util.arrays$arraylist.foreach(arrays.java:3880) at javabase.list.aslisttest.aslistadd(aslisttest.java:46) at javabase.list.aslisttest.main(aslisttest.java:20)
初始化一个字符串数组,将字符串数组转换为 list,在遍历list的时候进行移除和新增的操作
抛出异常信息unsupportedoperationexception。
根据异常信息java.lang.unsupportedoperationexception,我们看到他是从abstractlist里面出来的,让我们进入源码一看究竟
我们在什么时候调用到了这个 abstractlist 呢?
其实 arrays.aslist(arr) 返回的 arraylist 不是 java.util.arraylist,而是 arrays的内部类
private static class arraylist<e> extends abstractlist<e>
implements randomaccess, java.io.serializable{
private static final long serialversionuid = -2764017481108945198l;
private final e[] a;
arraylist(e[] array) {
a = objects.requirenonnull(array);
}
@override
public e get(int index) {}
@override
public e set(int index, e element) {...}
...
}
public abstract class abstractlist<e> extends abstractcollection<e> implements list<e> {
public boolean add(e e) {
add(size(), e);
return true;
}
public void add(int index, e element) {
throw new unsupportedoperationexception();
}
public e remove(int index) {
throw new unsupportedoperationexception();
}
}
他是没有实现 abstractlist 中的 add() 和 remove() 方法,这里就很清晰了为什么不支持新增和删除,因为根本没有实现。
3 对原始数组的修改会影响到我们获得的那个list
3.1 错误还原
一不小心修改了父list,却影响到了子list,在业务代码中,这会导致产生的数据发生变化,严重的话会造成影响较大的生产问题。
第二个坑的源码中,完成字符串数组转换为list之后,
我们将字符串数组的第三个对象的值修改为4,但是很奇怪在打印list的时候,发现list也发生了变化。
public static <t> list<t> aslist(t... a) {
return new arraylist<>(a);
}
arraylist(e[] array) {
a = objects.requirenonnull(array);
}aslist中创建了 arraylist,但是他直接引用了原本的数组对象
所以只要原本的数组对象一发生变化,list也跟着变化
所以在使用到引用的时候,我们需要特别的注意。
3.2 解决方案
重新new一个新的 arraylist 来装返回的 list
list strings = new arraylist<>(arrays.aslist(arr));
4 java.util.arraylist如果不正确操作也不支持增删操作
在第二个坑的时候,我们说到了 arrays.aslist 返回的 list 不支持增删操作,
是因为他的自己实现了一个内部类 arraylist,这个内部类继承了 abstractlist 没有实现 add() 和 remove() 方法导致操作失败。
但是第三个坑的时候,我们利用 java.util.arraylist 包装了返回的 list,进行增删操作还是会失败,那是为什么呢?
删除方法逻辑:

在foreach中操作增删,因为因为 modcount 会被修改,与第一步保存的数组修改次数不一致,抛出异常 concurrentmodificationexception
在正确操作是什么?总结了四种方式

5 arraylist中的 sublist 强转 arraylist 导致异常
阿里《java开发手册》上提过
[强制] arraylist的sublist结果不可強转成arraylist,否则会抛出classcastexception
异常,即java.util.randomaccessublist cannot be cast to java.util.arraylist.
说明: sublist 返回的是arraylist 的内部类sublist, 并不是arraylist ,而是
arraylist的一个视图,対于sublist子列表的所有操作最终会反映到原列表上。
private static void sublisttest(){
list<string> names = new arraylist<string>() {{
add("one");
add("two");
add("three");
}};
arraylist strings = (arraylist) names.sublist(0, 1);
system.out.println(strings.tostring());
}
exception in thread "main" java.lang.classcastexception: java.util.arraylist$sublist cannot be cast to java.util.arraylist
问题是有八九就是出现在sublist这个方法上了
private class sublist extends abstractlist<e> implements randomaccess {
private final abstractlist<e> parent;
private final int parentoffset;
private final int offset;
int size;
sublist(abstractlist<e> parent,
int offset, int fromindex, int toindex) {
this.parent = parent;
this.parentoffset = fromindex;
this.offset = offset + fromindex;
this.size = toindex - fromindex;
this.modcount = arraylist.this.modcount;
}
}
其实 sublist 是一个继承 abstractlist 的内部类,在 sublist 的构建函数中的将 list 中的部分属性直接赋予给自己
sublist 没有创建一个新的 list,而是直接引用了原来的 list(this.parent = parent),指定了元素的范围
所以 sublist 方法不能直接转成 arraylist,他只是arraylist的内部类,没有其他的关系
因为是引用的关系,所以在这里也需要特别的注意,如果对原来的list进行修改,会对产生的 sublist结果产生影响。
list<string> names = new arraylist<string>() {{
add("one");
add("two");
add("three");
}};
list strings = names.sublist(0, 1);
strings.add(0, "ongchange");
system.out.println(strings.tostring());
system.out.println(names.tostring());
[ongchange, one]
[ongchange, one, two, three]
对sublist产生的list做出结构型修改,操作会反应到原来的list上,ongchange也添加到了names中
如果修改原来的list则会抛出异常concurrentmodificationexception
list<string> names = new arraylist<string>() {{
add("one");
add("two");
add("three");
}};
list strings = names.sublist(0, 1);
names.add("four");
system.out.println(strings.tostring());
system.out.println(names.tostring());
exception in thread "main" java.util.concurrentmodificationexception
原因:
sublist的时候记录this.modcount为3

原来的list插入了一个新元素,导致this.modcount不第一次保存的不一致则抛出异常
解决方案:在操作sublist的时候,new一个新的arraylist来接收创建sublist结果的拷贝
list strings = new arraylist(names.sublist(0, 1));
6 arraylist中的sublist切片造成oom
6.1 问题还原
在业务开发中的时候,他们经常通过sublist来获取所需要的那部分数据
在上面的例子中,我们知道了sublist所产生的list,其实是对原来list对象的引用
这个产生的list只是原来list对象的视图,也就是说虽然值切片获取了一小段数据,但是原来的list对象却得不到回收,这个原来的list对象可能是一个很大的对象
为了方便我们测试,将vm调整一下 -xms20m -xmx40m
private static void sublistoomtest(){
intstream.range(0, 1000).foreach(i ->{
list<integer> collect = intstream.range(0, 100000).boxed().collect(collectors.tolist());
data.add(collect.sublist(0, 1));
});
}}
exception in thread "main" java.lang.outofmemoryerror: java heap space出现oom的原因,循环1000次创建了1000个具有10万个元素的list
因为始终被collect.sublist(0, 1)强引用,得不到回收
6.2 解决方案
1.在sublist方法返回sublist,重新使用new arraylist,来构建一个独立的arraylist
list list = new arraylist<>(collect.sublist(0, 1));
2.利用java8的stream中的skip和limit来达到切片的目的
list list = collect.stream().skip(0).limit(1).collect(collectors.tolist());
在这里我们可以看到,只要用一个新的容器来装结果,就可以切断与原始list的关系
7 linkedlist的插入速度不一定比arraylist快
学习数据结构的时候,我们就已经得出了结论
●对于数组,随机元素访问的时间复杂度是0(1), 元素插入操作是o(n);
●对于链表,随机元素访问的时间复杂度是o(n), 元素插入操作是0(1).
元素插入对于链表来说应该是他的优势
但是他就一定比数组快? 我们执行插入1000w次的操作
private static void test(){
stopwatch stopwatch = new stopwatch();
int elementcount = 100000;
stopwatch.start("arraylist add");
list<integer> arraylist = intstream.rangeclosed(1, elementcount).boxed().collect(collectors.tocollection(arraylist::new));
// arraylist插入数据
intstream.rangeclosed(0, elementcount).foreach(i ->arraylist.add(threadlocalrandom.current().nextint(elementcount), 1));
stopwatch.stop();
stopwatch.start("linkedlist add");
list<integer> linkedlist = intstream.rangeclosed(1, elementcount).boxed().collect(collectors.tocollection(linkedlist::new));
// arraylist插入数据
intstream.rangeclosed(0, elementcount).foreach(i -> linkedlist.add(threadlocalrandom.current().nextint(elementcount), 1));
stopwatch.stop();
system.out.println(stopwatch.prettyprint());
}
stopwatch '': running time = 44507882 ns
---------------------------------------------
ns % task name
---------------------------------------------
043836412 098% elementcount 100 arraylist add
000671470 002% elementcount 100 linkedlist add
stopwatch '': running time = 196325261 ns
---------------------------------------------
ns % task name
---------------------------------------------
053848980 027% elementcount 10000 arraylist add
142476281 073% elementcount 10000 linkedlist add
stopwatch '': running time = 26384216979 ns
---------------------------------------------
ns % task name
---------------------------------------------
978501580 004% elementcount 100000 arraylist add
25405715399 096% elementcount 100000 linkedlist add
看到在执行插入1万、10完次操作的时候,linkedlist的插入操作时间是 arraylist的两倍以上
那问题主要就是出现在linkedlist的 add()方法上
public void add(int index, e element) {
checkpositionindex(index);
if (index == size)
linklast(element);
else
linkbefore(element, node(index));
}
/**
* returns the (non-null) node at the specified element index.
*/
node<e> node(int index) {
// assert iselementindex(index);
if(index < (size >> 1)) {
node<e> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
node<e> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
linkedlist的 add()方法主要逻辑
通过遍历找到那个节点的node
执行插入操作
arraylist的 add()方法
public void add(int index, e element) {
rangecheckforadd(index);
ensurecapacityinternal(size + 1); // increments modcount!!
system.arraycopy(elementdata, index, elementdata, index + 1,
size - index);
elementdata[index] = element;
size++;
}
- 计算最小容量
- 最小容量大于数组对象,则进行扩容
- 进行数组复制,根据插入的index将数组向后移动一位
- 最后在空位上插入新值
根据试验的测试,我们得出了在实际的随机插入中,linkedlist并没有比arraylist的速度快
所以在实际的使用中,如果涉及到头尾对象的操作,可以使用linkedlist数据结构来进行增删的操作,发挥linkedlist的优势
最好再进行实际的性能测试评估,来得到最合适的数据结构。
8 copyonwritearraylist内存占用过多
copyonwrite,顾名思义就是写的时候会将共享变量新复制一份出来,这样做的好处是读操作完全无锁。
copyonwritearraylist的add()方法
public boolean add(e e) {
// 获取独占锁
final reentrantlock lock = this.lock;
lock.lock();
try {
// 获取array
object[] elements = getarray();
// 复制array到新数组,添加元素到新数组
int len = elements.length;
object[] newelements = arrays.copyof(elements, len + 1);
newelements[len] = e;
// 替换数组
setarray(newelements);
return true;
} finally {
// 释放锁
lock.unlock();
}
}
copyonwritearraylist 内部维护了一个数组,成员变量 array 就指向这个内部数组,所有的读操作都是基于新的array对象进行的。
因为上了独占锁,所以如果多个线程调用add()方法只有一个线程会获得到该锁,其他线程被阻塞,知道锁被释放, 由于加了锁,所以整个操作的过程是原子性操作
copyonwritearraylist 会将 新的array复制一份,然后在新复制处理的数组上执行增加元素的操作,执行完之后再将复制的结果指向这个新的数组。
由于每次写入的时候都会对数组对象进行复制,复制过程不仅会占用双倍内存,还需要消耗 cpu 等资源,所以当列表中的元素比较少的时候,这对内存和 gc 并没有多大影响,但是当列表保存了大量元素的时候,
对 copyonwritearraylist 每一次修改,都会重新创建一个大对象,并且原来的大对象也需要回收,这都可能会触发 gc,如果超过老年代的大小则容易触发full gc,引起应用程序长时间停顿。
9 copyonwritearraylist是弱一致性的
public iterator<e> iterator() {
return new cowiterator<e>(getarray(), 0);
}
static final class cowiterator<e> implements listiterator<e> {
/** snapshot of the array */
private final object[] snapshot;
/** index of element to be returned by subsequent call to next. */
private int cursor;
private cowiterator(object[] elements, int initialcursor) {
cursor = initialcursor;
snapshot = elements;
}
public boolean hasnext() {
return cursor < snapshot.length;
}
public boolean hasprevious() {
return cursor > 0;
}
@suppresswarnings("unchecked")
public e next() {
if (! hasnext())
throw new nosuchelementexception();
return (e) snapshot[cursor++];
}
调用iterator方法获取迭代器返回一个cowiterator对象
cowiterator的构造器里主要是 保存了当前的list对象的内容和遍历list时数据的下标。
snapshot是list的快照信息,因为copyonwritearraylist的读写策略中都会使用getarray()来获取一个快照信息,生成一个新的数组。
所以在使用该迭代器元素时,其他线程对该lsit操作是不可见的,因为操作的是两个不同的数组所以造成弱一致性。
private static void copyonwritearraylisttest(){
copyonwritearraylist<string> list = new copyonwritearraylist();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
thread thread = new thread(() -> {
system.out.println(">>>> start");
list.add(1, "replacetest");
list.remove(2);
});
// 在启动线程前获取迭代器
iterator<string> iterator = list.iterator();
thread.start();
try {
// 等待线程执行完毕
thread.join();
} catch (interruptedexception e) {
e.printstacktrace();
}
while (iterator.hasnext()){
system.out.println(iterator.next());
}
}
>>>> start
test1
test2
test3
test4
上面的demo中在启动线程前获取到了原来list的迭代器,
在之后启动新建一个线程,在线程里面修改了第一个元素的值,移除了第二个元素
在执行完子线程之后,遍历了迭代器的元素,发现子线程里面操作的一个都没有生效,这里提现了迭代器弱一致性。
10 copyonwritearraylist的迭代器不支持增删改
private static void copyonwritearraylisttest(){
copyonwritearraylist<string> list = new copyonwritearraylist<>();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
iterator<string> iterator = list.iterator();
while (iterator.hasnext()){
if ("test1".equals(iterator.next())){
iterator.remove();
}
}
system.out.println(list.tostring());
}
exception in thread "main" java.lang.unsupportedoperationexception
at java.util.concurrent.copyonwritearraylist$cowiterator.remove(copyonwritearraylist.java:1178)
copyonwritearraylist 迭代器是只读的,不支持增删操作
copyonwritearraylist迭代器中的 remove()和 add()方法,没有支持增删而是直接抛出了异常
因为迭代器遍历的仅仅是一个快照,而对快照进行增删改是没有意义的。
/**
* not supported. always throws unsupportedoperationexception.
* @throws unsupportedoperationexception always; {@code remove}
* is not supported by this iterator.
*/
public void remove() {
throw new unsupportedoperationexception();
}
/**
* not supported. always throws unsupportedoperationexception.
* @throws unsupportedoperationexception always; {@code set}
* is not supported by this iterator.
*/
public void set(e e) {
throw new unsupportedoperationexception();
}
/**
* not supported. always throws unsupportedoperationexception.
* @throws unsupportedoperationexception always; {@code add}
* is not supported by this iterator.
*/
public void add(e e) {
throw new unsupportedoperationexception();
}
11 总结
由于篇幅的限制,我们只对一些在业务开发中常见的关键点进行梳理和介绍
在实际的工作中,我们不单单是要清除不同类型容器的特性,还要选择适合的容器才能做到事半功倍。
我们主要介绍了arrays.aslist转换过程中的一些坑,以及因为操作不当造成的oom和异常,
到最后介绍了线程安全类copyonwritearraylist的一些坑,让我们认识到在丰富的api下藏着许多的陷阱。
在使用的过程中,需要更加充分的考虑避免这些隐患的发生。
最后一张思维导图来回顾一下~

到此这篇关于java中list的10个坑的文章就介绍到这了,更多相关java中list坑内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论