#Java集合:ArrayList @FDDLC
发布日期:2021-06-30 20:58:22 浏览次数:2 分类:技术文章

本文共 1976 字,大约阅读时间需要 6 分钟。

一、ArrayList在集合家族中的地位

从上图可以看出,ArrayList是List的后代,而List又是Collection的后代,所以ArrayList拥有List和Collection的方法。

有关List和Collection的介绍,可以参考:

 

二、ArrayList常用的方法

1、clone方法(继承自Object):

注意:虽然Object是其他所有类的直接或间接父类,但Object后代中不一定拥有clone方法!(自己实现了才有)

public Object clone() {    try {        ArrayList
v = (ArrayList
) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); }}

关于elementData:

示例:

a、代码示例import java.util.*;public class Main{    public static void main(String[] args) {        ArrayList
arrayList=new ArrayList<>(); arrayList.addAll(Arrays.asList(new Integer[]{1,2,3})); ArrayList
arrayList_copy=(ArrayList
)arrayList.clone(); //需要强转! System.out.println("arrayList:"+arrayList); System.out.println("arrayList_copy:"+arrayList_copy); System.out.println("arrayList:"+Integer.toHexString(arrayList.hashCode())); System.out.println("arrayList_copy:"+Integer.toHexString(arrayList_copy.hashCode())); System.out.println("arrayList==arrayList_copy:"+(arrayList==arrayList_copy)); //比较物理地址,很显然,这是两个不同的对象,物理地址当然不一样! ArrayList
ref_copy=arrayList; System.out.println("ref_copy==arrayList:"+(ref_copy==arrayList)); //ref_copy只是拷贝了arrayList的引用,所以二者都指向同一个对象,物理地址相同! System.out.println("Objects.equals:"+Objects.equals(arrayList,arrayList_copy)); System.out.println("Objects.deepEquals:"+Objects.deepEquals(arrayList,arrayList_copy)); }}b、输出arrayList:[1, 2, 3]arrayList_copy:[1, 2, 3]arrayList:7861arrayList_copy:7861arrayList==arrayList_copy:falseref_copy==arrayList:trueObjects.equals:trueObjects.deepEquals:true

总结:clone方法是复制了一个新的对象,且新对象的内容和原件一样,相当于复印!

拓展:

 

2、ArrayList最多能添加多少个元素呢?

 

3、不好意思,没了。。。常用的方法基本都在它的super类里定义完了,它自个儿还真没几个常用的方法。有关List和Collection的介绍,可以参考:

 

 

 

 

 

 

 

 

 

 

 

 

转载地址:https://liuxingchang.blog.csdn.net/article/details/109433318 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:#DeepClone、Clone #深复制、浅复制 #深拷贝、浅拷贝 @FDDLC
下一篇:#LeetCode215. 数组中的第K个最大元素 @FDDLC

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月06日 21时15分08秒