集合类中的Collection接口实现类
今天学习一下集合包里面的内容,常见的有Collection和Map两个接口的实现类
Collection中常见的又分为两种:
1.List ,支持放入重复的对象,实现类有arraylist,linkedlist,vector,stack
2.Set ,不支持放入重复对象,hashset,treeset
ArrayList:
创建arraylist:提供了三种构造方式。
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];//大于0时就直接创建object数组
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;//为0时构造一个空的
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
当插入的数据大于它的容量时就会扩容,过程如下:
public static void main(String[] args) {
List list = new ArrayList(2);
list.add(1);
list.add(2);
list.add(3);
}
上面定义了长度为2,但存放了三个,调用过程是这样的,在第三次时决断minCapacity-elementData.length>0就调用grow法。源码如下:
//添加
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
} private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
} private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
} private void ensureExplicitCapacity(int minCapacity) {
modCount++; // overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
} private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
删除元素:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
遍历时:
public Iterator<E> iterator() {
return new Itr();
}
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();//这个异常说明在操作元素时,有其他线程对list进行了改变
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
总结:
ArrayList基于数组方式实现,无容量限制,在插入元素时可能会扩容,在删除元素时,容量大小并不会改变,但可以通过trimToSize()来修改。在查找元素时要遍历数组,对于非null的元素,采取equals的方式查找,最后一点arrayList是非线程安全的。
LinkedList也是非线程安全的,它基于双向链表机制实现,插入元素时要新建一个Entry对象(1.8好像是Node,没骨找到Entry对象)。
Vector是基于Synchronized实现的线程安全的ArrayList,但在插入元素时容量扩充的机制和ArrayList稍有不同,并可通过capacityIncrement来控制容量的扩充。
Stack继承Vector,实现后进先出(LIFO)的弹出及压入操作,提供了push,pop,peek三个主要方法。
HashSet:
hashset是set接口的实现,set 和list区别就是set不允许有元素重复(不重复是底层用hashmap),
总结:
HashSet基于HashMap,无容量限制,HashSet是非线程安全的。
集合类中的Collection接口实现类的更多相关文章
- 『Java』Collection接口 Collections类
接口Collection public interface Collection<E>定义了所有单列集合中共性的方法,所有的单列集合都可以使用共性方法. Collection的常用子接口有 ...
- JavaWeb学习之JDBC API中常用的接口和类
JDBC API中包含四个常用的接口和一个类分别是: 1.Connection接口 2.Statement接口 3.PreparedStatement接口 4.ResultSet接口 5.Driver ...
- Java中的List接口实现类LinkedList
package collection; import java.util.LinkedList; /* * 1.implement List接口 * 2.底层是一个链表结构:查询慢,增删快 * 注意: ...
- 集合框架二(Collection接口实现类常用遍历方法)
四种常用遍历方式 Collection coll = new ArrayList(); coll.add("123"); coll.add("456"); co ...
- JAVA中Collection接口和Map接口的主要实现类
Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements).一些Collection允许相同的元素 ...
- JAVA 中的 Collection 和 Map 以及相关派生类的概念
JAVA中Collection接口和Map接口的主要实现类 Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的 ...
- 牛客网Java刷题知识点之Java 集合框架的构成、集合框架中的迭代器Iterator、集合框架中的集合接口Collection(List和Set)、集合框架中的Map集合
不多说,直接上干货! 集合框架中包含了大量集合接口.这些接口的实现类和操作它们的算法. 集合容器因为内部的数据结构不同,有多种具体容器. 不断的向上抽取,就形成了集合框架. Map是一次添加一对元素. ...
- 16、Collection接口及其子接口Set和List(常用类LinkedList,ArrayList,Vector和Stack)
16.Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements).一些Collection允许相同 ...
- 【集合系列】- 深入浅出分析Collection中的List接口
一.List简介 List 的数据结构就是一个序列,存储内容时直接在内存中开辟一块连续的空间,然后将空间地址与索引对应. 以下是List集合简易架构图 由图中的继承关系,可以知道,ArrayList. ...
随机推荐
- codeforces 848A - From Y to Y(构造)
原题链接:http://codeforces.com/problemset/problem/848/A 题意:让我们构造一个字符串.这里有一种操作:取走这个字符串的若干部分,分成两部分,然后将这两部分 ...
- Java总结第二期
大家好,我又来了!!啦啦,我知道你们很想我,很想我赶快写更多的文章来提高自己的水平,好吧,我就从了你们.下面跟我一起来光顾Java第二期,掌声,掌声!!! 第二章: 这章,我要给大家讲得内容有变量,常 ...
- delphi中如何将一整个文件读入内存
来源 https://bbs.csdn.net/topics/390985048 分配一块大内存吧,要是一下申请不了64M那么大,就多申请几块小的,用个链表连起来.用FileStream类的方法读取文 ...
- vue.js循环语句
vue.js循环语句 循环使用 v-for 指令. v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组, site 是数组元素迭代的别名. v-for 可以 ...
- JPA project Change Event Handler问题解决
eclipse使用的是有经常会出现JPA project Change Event Handler(watering)很卡 网上的解决办法是 [Help > Installation Detai ...
- selenium2-java 浏览器cookie的获取
//成功登陆后增加如下代码 File cookieFile = new File("C:\\tmp\\tangdai.cookie.txt"); ...
- js对象传到后台ACTION使用
需的包 <script type="text/javascript" src="s"></script>gson-1.2.3.jar谷歌 ...
- JMeter的那些问题
我们从以下几个点来看jmeter: 1.jmeter是什么? 2.jmeter为什么我们要使用jmeter?他可以帮我们解决那些事情? 3.怎样使用jmeter做这些事情? 4.我们在什么时候会使用j ...
- [CF1228] 简要题解
A 题意 求\(l \le x \le r\)的所有数位不同的数\(x\), 任意输出一个. \(1 \leq l \leq r \leq 10 ^5\) Solution 按照题意模拟即可. #in ...
- MySQL 基础 20191025
1.MySQL(绿色软件)的安装后: (老师课件中的) 要设置字符集不然会报 1344 错误码,有两种: 为上面的还有一种为: set names 'utf8'; 2.MySQL管理 创建数据库 CR ...