为什么 Arrays.asList() 返回它自己的 ArrayList 实现 [英] Why does Arrays.asList() return its own ArrayList implementation

查看:26
本文介绍了为什么 Arrays.asList() 返回它自己的 ArrayList 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现 Java 中实际上有 2 种不同的 ArrayList 实现(我猜迟到总比没有好......).

I recently found out that there are actually 2 different ArrayList implementations in Java (better late than never I guess...).

所以我想知道为什么 Arrays.asList(T... a) 需要返回一个不能调整大小的列表?如果他们需要一个不可修改的列表,为什么要添加 set(int index, E element) 方法呢?

So I was wondering why does Arrays.asList(T... a) need to return a list which can not be resized ? If they needed an unmodifiable list why add the set(int index, E element) method then ?

所以我的一般问题是为什么不从 Arrays.asList(T... a) 方法返回 java.util.ArrayList ?

So my general question is why not return the java.util.ArrayList from the Arrays.asList(T... a) method ?

此外,您从 java.util.Arrays.ArrayList 实现中获得了什么?

Also what do you gain with the java.util.Arrays.ArrayList implementation ?

推荐答案

你问:

还有什么好处java.util.Arrays.ArrayList实施?

Also what do you gain with the java.util.Arrays.ArrayList implementation ?

这是因为Arrays.asList返回的Arrays$ArrayList只是对原始数组的一个视图.因此,当原始数组更改时,视图也会更改.

It is because the Arrays$ArrayList returned by Arrays.asList is just a view on the original array. So when the original array is changed then the view is changed too.

如果使用真正的 ArrayList,则元素将被复制,原始数组的更改不会影响 ArrayList.

If one would use an real ArrayList then the elements will be copied, and a change on the orignal array would not infuence the ArrayList.

这样做的原因很简单:

  • 性能:无需复制任何内容
  • 内存效率高:不需要第二个数组

这篇关于为什么 Arrays.asList() 返回它自己的 ArrayList 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆