◎筱米加步枪◎.Blog

Happy coding

关于Arrays.asList的问题

筱米加步枪 posted @ 2010年12月02日 05:06 in [ JavaSE ] with tags Arrays asList , 2551 阅读

将数组转成List问题,通常我们习惯这样写成:List<String> list = Arrays.asList("1","2");

于是我们这样就得到了一个list,但是这个List的实现类是java.util.Arrays.ArrayList这个类(而不是java.util.ArrayList)。

剖析JDK源代码可以发现,java.util.Arrays.ArrayList(就是转换出来list)它是继承了java.util.AbstractList这个类。

再来看看java.util.AbstractList类是啥样子的?可以发现

public E set(int index, E element)

public E set(int index, E element)

public E remove(int index)

public void add(int index, E element)  | public boolean add(E e)调用add(int index, E element)

以上方法的实现全部是抛出UnsupportedOperationException异常。

因此有Arrays.asList转换出来的List他其实是一个AbstractList,他可以像List一样访问,但是不可其做任何修改操作。

这也说明了,为什么Arrays.asList出来的List,对其做add、remove操作为抛出UnsupportedOperationException异常,从JDK代码角度上,原因在此。

换句话说,其实java.util.Arrays.ArrayList其实只是对数组做了一个装饰,可以看到里面的实现,E get(int index)、E set(int index, E element)等方法都是对数组的操作,他的目的只是提供了可以像访问List那样来访问数组而已。本质上其实还是一个数组。

  • 无匹配
  • 无匹配
civaget 说:
2023年12月12日 09:48

I'm impressed with 백링크업체's content marketing. Their content attracts backlinks and boosts authority.

civaget 说:
2023年12月16日 02:24

I've been searching for 수원출장마사지 services, and this article convinced me to give it a try. Thanks for the info!

civaget 说:
2023年12月16日 23:08

인천오피's aromatherapy sessions are a true sensory delight. I leave feeling calm and refreshed every time. The ultimate relaxation experience in Incheon!

civaget 说:
2023年12月23日 02:05

Discover soccer like never before with 축구중계.

civaget 说:
2024年1月14日 21:08

Hello! I would like to provide a enormous thumbs up for your fantastic information you’ve got here about this post. I will be coming back to your website to get more detailed soon. เว็บบอลคืนยอดเสียq


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter