Java集合-ArrayList
参考文献
ArrayList-JDK8
属性
1 | /** |
构造函数
1 | /** |
添加方法
1 | /** |
1 | /** |
1 | /** |
获取元素
1 | /** |
删除元素
1 | /** |
1 | /** |
序列化
1 | /** |
Fail-Fast
机制
- ArrayList也采用了快速失败的机制,通过记录modCount参数来实现.在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险.
ArrayList
中的elementData
为什么被修饰transient
-
在Java中,
ArrayList
是一个动态数组,用来存储一组对象.在ArrayList
的实现中,有一个成员变量elementData
用来存储实际的元素数据.这个变量被声明为transient
,原因是ArrayList
类实现了Serializable接口,需要将对象序列化并保存到磁盘或网络中,而elementData
不需要被序列化,因此需要将其标记为transient
. -
当一个
ArrayList
对象被序列化时,Java会将其所有的非transient
成员变量都保存到序列化流中,以便在反序列化时重新构造对象.而被transient
修饰的变量不会被保存到序列化流中,因此在反序列化时,这些变量的值将被初始化为默认值(如0、false、null等).对于ArrayList
来说,如果不将elementData
标记为transient
,那么序列化时会将整个数组保存到序列化流中,占用大量的存储空间,而在反序列化时,需要重新构造这个数组,增加了反序列化的时间和存储开销. -
需要注意的是,
elementData
被声明为private
,因此只有ArrayList
类内部才能访问它.当ArrayList
对象被序列化时,Java会调用ArrayList
的writeObject()
方法,该方法会将elementData
数组的内容写入序列化流中.在反序列化时,Java会调用ArrayList
的readObject()
方法,该方法会从序列化流中读取elementData
数组的内容,并重新构造ArrayList
对象. -
综上所述,将
elementData
标记为transient
可以减少序列化和反序列化时的存储空间和时间开销,提高程序的性能和效率.
有哪几种实现ArrayList
线程安全的方法
- 使用
Collection.synchronizedList
包装ArrayList
,然后操作包装后的list
- 使用
CopyOnWriteArrayList
代替ArrayList
- 使用
ArrayList
时,应用程序通过同步机制去控制ArrayList
的读写
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 HoleLin's Blog!