subList和asList
subList
subList返回仅仅只是一个视图。直接上源码
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
subListRangeCheck方式是判断fromIndex、toIndex是否合法,如果合法就直接返回一个subList对象,注意在产生该new该对象的时候传递了一个参数 this ,该参数非常重要,因为他代表着原始list。
/**
* 继承AbstractList类,实现RandomAccess接口
*/
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;
} //set方法
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
} //get方法
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
} //add方法
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
} //remove方法
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
}
该SubLsit是ArrayList的内部类,它与ArrayList一样,都是继承AbstractList和实现RandomAccess接口。同时也提供了get、set、add、remove等list常用的方法。但是它的构造函数有点特殊,在该构造函数中有两个地方需要注意:
1、this.parent = parent;而parent就是在前面传递过来的list,也就是说this.parent就是原始list的引用。
2、this.offset = offset + fromIndex;this.parentOffset = fromIndex;。同时在构造函数中它甚至将modCount(fail-fast机制)传递过来了。
我们再看get方法,在get方法中return ArrayList.this.elementData(offset + index);这段代码可以清晰表明get所返回就是原列表offset + index位置的元素。同样的道理还有add方法里面的:
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
remove方法里面的
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
诚然,到了这里我们可以判断subList返回的SubList同样也是AbstractList的子类,同时它的方法如get、set、add、remove等都是在原列表上面做操作,它并没有像subString一样生成一个新的对象。所以subList返回的只是原列表的一个视图,它所有的操作最终都会作用在原列表上。
从上面我们知道subList生成的子列表只是原列表的一个视图而已,如果我们操作子列表它产生的作用都会在原列表上面表现,但是如果我们操作原列表会产生什么情况呢?
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
//通过subList生成一个与list1一样的列表 list3
List<Integer> list3 = list1.subList(0, list1.size());
//修改list3
list1.add(3);
System.out.println("list1'size:" + list1.size());
System.out.println("list3'size:" + list3.size());//子视图里有modcount比较校验
}
该实例如果不产生意外,那么他们两个list的大小都应该都是3,但是偏偏事与愿违,事实上我们得到的结果是这样的:
list1'size:3
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(Unknown Source)
at java.util.ArrayList$SubList.size(Unknown Source)
at com.chenssy.test.arrayList.SubListTest.main(SubListTest.java:17)
list1正常输出,但是list3就抛出ConcurrentModificationException异常。我们再看size方法:
public int size() {
checkForComodification();
return this.size;
}
size方法首先会通过checkForComodification验证,然后再返回this.size。
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
该方法表明当原列表的modCount与this.modCount不相等时就会抛出ConcurrentModificationException。同时我们知道modCount 在new的过程中 "继承"了原列表modCount,只有在修改该列表(子列表)时才会修改该值(先表现在原列表后作用于子列表)。而在该实例中我们是操作原列表,原列表的modCount当然不会反应在子列表的modCount上啦,所以才会抛出该异常。
对于子列表视图,它是动态生成的,生成之后就不要操作原列表了,否则必然都导致视图的不稳定而抛出异常。最好的办法就是将原列表设置为只读状态,要操作就操作子列表:
//通过subList生成一个与list1一样的列表 list3
List<Integer> list3 = list1.subList(0, list1.size()); //对list1设置为只读状态
list1 = Collections.unmodifiableList(list1);
在开发过程中我们一定会遇到这样一个问题:获取一堆数据后,需要删除某段数据。例如,有一个列表存在1000条记录,我们需要删除100-200位置处的数据,我们可以这样处理:
子列表的操作都会反映在原列表上。所以下面一行代码全部搞定:
list1.subList(100, 200).clear();
asList
1.在使用asList时不要将基本数据类型当做参数。
2.asList返回的列表只不过是一个披着list的外衣(Arrays里面的内部类ArrayList),它并没有list的基本特性(变长)。该list是一个长度不可变的列表,传入参数的数组有多长,其返回的列表就只能是多长。
//入参需要是泛型
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
} //基本类型不能当泛型传入,而数组可以,所以个数是一个,类型是数组
public static void main(String[] args) {
int[] ints = {1,2,3,4,5};
List list = Arrays.asList(ints);
System.out.println("list'size:" + list.size());
System.out.println("list 的类型:" + list.get(0).getClass());
System.out.println("list.get(0) == ints:" + list.get(0).equals(ints));
}
--------------------------------------------
outPut:
list'size:1
list 的类型:class [I
list.get(0) == ints:true //正确方式,Integer可以是泛型
public static void main(String[] args) {
Integer[] ints = {1,2,3,4,5};
List list = Arrays.asList(ints);
System.out.println("list'size:" + list.size());
System.out.println("list.get(0) 的类型:" + list.get(0).getClass());
System.out.println("list.get(0) == ints[0]:" + list.get(0).equals(ints[0]));
}
----------------------------------------
outPut:
list'size:5
list.get(0) 的类型:class java.lang.Integer
list.get(0) == ints[0]:true
使用工具类 Arrays.asList()把数组转换成集合时,不能使用其修改集合相关的方 法,它的 add/remove/clear 方法会抛出 UnsupportedOperationException 异常。 说明:asList 的返回对象是一个 Arrays 内部类,并没有实现集合的修改方法。Arrays.asList 体现的是适配器模式,只是转换接口,后台的数据仍是数组。
String[] str = new String[] { "a", "b" };
List list = Arrays.asList(str);
第一种情况:list.add("c"); 运行时异常。
第二种情况:str[0]= "jinyong"; 那么 list.get(0)也会随之修改
subList和asList的更多相关文章
- Collections类常用方法总结
1. sort 对集合进行排序 public static <T extends Comparable<? super T>> void sort(List<T> ...
- thinking in java之Collections工具类的使用
代码摘自<thinking in java>4td 此实例非常好的总结了Collections的一些常见方法的使用. package countainers; import java.ut ...
- Java 容器在实际项目开发中应用
前言:在java开发中我们离不开集合数组等,在java中有个专有名词:"容器" ,下面会结合Thinking in Java的知识和实际开发中业务场景讲述一下容器在Web项目中的用 ...
- 【Java集合的详细研究1】Collections类常用方法总结
1.sort(Collection)方法的使用(含义:对集合进行排序). 例:对已知集合c进行排序? public class Practice { public static void main(S ...
- Collections常用方法总结
public class CollectionsTest { public static void main(String[] args) { List<Integer> list = n ...
- Java集合操作类Collections的一些常用方法
public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); ...
- Java知识点梳理——常用方法总结
1.查找字符串最后一次出现的位置 String str = "my name is zzw"; int lastIndex = str.lastIndexOf("zzw& ...
- Java 学习(21):Java 实例
Java 实例 本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用. Java 环境设置实例 //HelloWorld.java 文件 public cla ...
- Collection 和 Collections的区别
1.java.util.Collection 是一个集合接口(集合类的一个顶级接口).它提供了对集合对象进行基本操作的通用接口方法.Collection接口在Java 类库中有很多具体的实现.Coll ...
随机推荐
- 《深入PHP与jQuery开发》读书笔记——Chapter3
<深入PHP与jQuery开发>第三章学习笔记 1.PHP的魔术方法(在对象中发生某些例行事件时会自动调用这些方法) PHP提供了魔术方法__construct()(构造函数),在新对象被 ...
- 使用多种方式实现遍历HashMap
今天讲解的主要是使用多种方式来实现遍历HashMap取出Key和value,首先在java中如果想让一个集合能够用for增强来实现迭代,那么此接口或类必须实现Iterable接口,那么Iterable ...
- 破解LR时,解决loadrunner 破解错误:license security violation.Operation is not allowed
一.由于在压力测试执行中,出现一个-10803的错误 ,为解决这个错误,重新设置的环境变量,在次执行错误,这个问题解决了,但另外一个问题出来了,LR,打开脚本编辑器老提示找不到TEMP目录,当时没有想 ...
- 搭建DNS服务器
导读 Linux下架设DNS服务器通常是使用Bind程序来实现的.Bind是一款实现DNS服务器的开放源码的软件.DNS即域名系统,主要功能是将人们易于记忆的Domain Name(域名)与不易记忆的 ...
- unity3d web.config设置
原地址:http://www.cnblogs.com/88999660/archive/2013/03/22/2976105.html <?xml version="1.0" ...
- System.SysUtils.TMarshaller 与 System.TMarshal
转自:http://www.cnblogs.com/del/archive/2013/06/10/3130974.html TMarshaller(结构) 基于 TMarshal(是有一大堆的 cla ...
- 【leetcode】3Sum
3Sum Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find a ...
- 【读书笔记】读《JavaScript设计模式》之门面模式
一.前言 门面模式,也称Facade(外观)模式.核心的两点作用—— 1> 简化类的接口(让接口变得更加容易理解.容易应用.更加符合对应业务),来掩盖一个非常不同或者复杂的实现 2> 消除 ...
- Android之shape属性详解
有时候 ,为了满足一些需求,我们要用到 shape 去定义 一些背景,shape 的用法 跟图片一样 ,可以给View设置 Android:background="@drawable/sha ...
- ASP.NET之AreaRegistration
ASP.NETMVC的AreaRegistration是用来干什么呢? 它是用来提供一个很好的接口让我们可以将Controller定义在其他的Library项目中,这主要可以用来解决模块化开发:一般情 ...