集合类中的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. ...
随机推荐
- 线程join方法demo-模拟叫号看病
package cn.chapter4.test5; public class SicknessDemo { /** * 模拟叫号看病 * @param args * * 思路:把普通号看病写在主线程 ...
- 学习总结-Redis
一,简介 redis(Remote Dictionary Server)是一种Nosql技术,它是一个开源的高级kv存储和数据结构存储系统,它经常被拿来和Memcached相比较,但是Memcache ...
- PCB学习
一.PCB设置 在线DRC:自动更正,会提示短路. 对象捕捉>>智能元件snap,可以智能抓取中心点,勾选 智能TrackEnds: 撤销重做:30步 旋转步骤:90.000(可以按空格旋 ...
- 手机上访问angular移动项目
要实现手机访问本地开发的移动端项目,首先做到两点: 1.本地打开的项目可以使用本地ip访问 2.手机和电脑同时处于一个同一个局域网中(手机和电脑同时连上同一个wifi / 手机开热点给电脑 / 电脑开 ...
- textarea 根据光标位置添加内容
// 获取焦点 let txt = document.getElementById("countRule"); let temp = txt.value; txt.focus(); ...
- APP测试之-网址
App测试那么多机型怎么搞? http://www.jianshu.com/p/1a9aa2cf0d85 移动App的分类 http://www.jianshu.com/p/01f5db8958d2 ...
- [CSP-S模拟测试]:密州盛宴(贪心)
江城子·密州出猎老夫聊发少年狂,左牵黄,右擎苍,锦帽貂裘,千骑卷平冈.为报倾城随太守,亲射虎,看孙郎.酒酣胸胆尚开张,鬓微霜,又何妨!持节云中,何日遣冯唐?会挽雕弓如满月,西北望,射天狼.(这首词通过 ...
- 前端每日实战:24# 视频演示如何用纯 CSS 创作出平滑的层叠海浪特效
效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/JvmBdE 可交互视频教程 此视频 ...
- appium常见问题02_android内嵌H5页(webview)如何定位
现在大多数app都是由原生页面和内嵌H5(即webview)组成,app原生页面直接定位即可,那内嵌H5页面要如何定位呢. 相信大多数人用appium做自动化时都有遇到这个问题,小编总结了下工作中该问 ...
- luoguP1084 疫情控制(题解)(搜索+贪心)
luoguP1084 疫情控制 题目 #include<iostream> #include<cstdlib> #include<cstdio> #include& ...