Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

java - Why does Arrays.asList() return its own ArrayList implementation

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

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 ?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You asked:

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

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.

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.

The reasons to do this are quite simple:

  • performance: no need to copy anyting
  • memory efficent: no second array is needed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...