- 浏览: 459589 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
ty1972873004:
sunwang810812 写道我运行了这个例子,怎么结果是这 ...
Java并发编程: 使用Semaphore限制资源并发访问的线程数 -
lgh1992314:
simpleDean 写道请问,Logger.setLevel ...
Java内置Logger详解 -
sunwang810812:
我运行了这个例子,怎么结果是这样的:2号车泊车6号车泊车5号车 ...
Java并发编程: 使用Semaphore限制资源并发访问的线程数 -
jp260715007:
nanjiwubing123 写道参考你的用法,用如下方式实现 ...
面试题--三个线程循环打印ABC10次的几种解决方法 -
cb_0312:
SurnameDictionary文章我没看完,现在懂了
中文排序
Arrays工具类提供了一些比较实用的方法,比如sort, binarySearch, fill等。其中还有一个asList方法,此方法能够将一个变长参数或者数组转换成List。
但是,这个生成的List,它是固定长度的,如果对其进行add或者remove的操作,会抛出UnsupportedOperationException,为什么会这样呢?
带着疑问,查看一下Arrays的源码,可以得到问题的结果。
方法asList返回的是new ArrayList<T>(a)。但是,这个ArrayList并不是java.util.ArrayList,它是一个Arrays类中的重新定义的内部类。
具体的实现如下:
从这个内部类ArrayList的实现可以看出,它继承了类AbstractList<E>,但是没有重写add和remove方法,没有给出具体的实现。查看一下AbstractList类中对add和remove方法的定义,如果一个list不支持add和remove就会抛出UnsupportedOperationException。
至此,为什么Arrays.asList产生的List是不可添加或者删除,否则会产生UnsupportedOperationException,就可以得到解释了。
如果我们想把一个变长或者数据转变成List, 而且期望这个List能够进行add或者remove操作,那该怎么做呢?
我们可以写一个类似的方法,里面直接采用java.util.ArrayList即可。
比如:
测试代码如下:
输出结果:
[Larry, Moe, Curly]
[[Spring, Summer, Autumn, Winter]]
[Larry, Moe, Curly, Hello]
但是,这个生成的List,它是固定长度的,如果对其进行add或者remove的操作,会抛出UnsupportedOperationException,为什么会这样呢?
带着疑问,查看一下Arrays的源码,可以得到问题的结果。
/** * Returns a fixed-size list backed by the specified array. (Changes to * the returned list "write through" to the array.) This method acts * as bridge between array-based and collection-based APIs, in * combination with <tt>Collection.toArray</tt>. The returned list is * serializable and implements {@link RandomAccess}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); * </pre> * * @param a the array by which the list will be backed. * @return a list view of the specified array. * @see Collection#toArray() */ public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); }
方法asList返回的是new ArrayList<T>(a)。但是,这个ArrayList并不是java.util.ArrayList,它是一个Arrays类中的重新定义的内部类。
具体的实现如下:
/** * @serial include */ private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L; private Object[] a; ArrayList(E[] array) { if (array==null) throw new NullPointerException(); a = array; } public int size() { return a.length; } public Object[] toArray() { return (Object[])a.clone(); } public E get(int index) { return (E)a[index]; } public E set(int index, E element) { Object oldValue = a[index]; a[index] = element; return (E)oldValue; } public int indexOf(Object o) { if (o==null) { for (int i=0; i<a.length; i++) if (a[i]==null) return i; } else { for (int i=0; i<a.length; i++) if (o.equals(a[i])) return i; } return -1; } public boolean contains(Object o) { return indexOf(o) != -1; } }
从这个内部类ArrayList的实现可以看出,它继承了类AbstractList<E>,但是没有重写add和remove方法,没有给出具体的实现。查看一下AbstractList类中对add和remove方法的定义,如果一个list不支持add和remove就会抛出UnsupportedOperationException。
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractList() { } /** * Appends the specified element to the end of this List (optional * operation). <p> * * This implementation calls <tt>add(size(), o)</tt>.<p> * * Note that this implementation throws an * <tt>UnsupportedOperationException</tt> unless <tt>add(int, Object)</tt> * is overridden. * * @param o element to be appended to this list. * * @return <tt>true</tt> (as per the general contract of * <tt>Collection.add</tt>). * * @throws UnsupportedOperationException if the <tt>add</tt> method is not * supported by this Set. * * @throws ClassCastException if the class of the specified element * prevents it from being added to this set. * * @throws IllegalArgumentException some aspect of this element prevents * it from being added to this collection. */ public boolean add(E o) { add(size(), o); return true; } /** * Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices).<p> * * This implementation always throws an UnsupportedOperationException. * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * * @throws UnsupportedOperationException if the <tt>add</tt> method is not * supported by this list. * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException index is out of range (<tt>index < * 0 || index > size()</tt>). */ public void add(int index, E element) { throw new UnsupportedOperationException(); } /** * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list.<p> * * This implementation always throws an * <tt>UnsupportedOperationException</tt>. * * @param index the index of the element to remove. * @return the element previously at the specified position. * * @throws UnsupportedOperationException if the <tt>remove</tt> method is * not supported by this list. * @throws IndexOutOfBoundsException if the specified index is out of * range (<tt>index < 0 || index >= size()</tt>). */ public E remove(int index) { throw new UnsupportedOperationException(); } }
至此,为什么Arrays.asList产生的List是不可添加或者删除,否则会产生UnsupportedOperationException,就可以得到解释了。
如果我们想把一个变长或者数据转变成List, 而且期望这个List能够进行add或者remove操作,那该怎么做呢?
我们可以写一个类似的方法,里面直接采用java.util.ArrayList即可。
比如:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MyArrays { public static <T> List<T> asList(T... a) { List<T> list = new ArrayList<T>(); Collections.addAll(list, a); return list; } }
测试代码如下:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Test { @SuppressWarnings("unchecked") public static void main(String[] args) { List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); print(stooges); List<List<String>> seasonsList = Arrays.asList(retrieveSeasonsList()); print(seasonsList); /* * 自己实现一个asList方法,能够添加和删除。 */ List<String> list = MyArrays.asList("Larry", "Moe", "Curly"); list.add("Hello"); print(list); } private static <T> void print(List<T> list) { System.out.println(list); } private static List<String> retrieveSeasonsList() { List<String> seasonsList = new ArrayList<String>(); seasonsList.add("Spring"); seasonsList.add("Summer"); seasonsList.add("Autumn"); seasonsList.add("Winter"); return seasonsList; } }
输出结果:
[Larry, Moe, Curly]
[[Spring, Summer, Autumn, Winter]]
[Larry, Moe, Curly, Hello]
发表评论
-
工厂类中移除if/else语句
2016-07-10 19:52 846面向对象语言的一个强大的特性是多态,它可以用来在代码中移除 ... -
Java编程练手100题
2014-12-11 17:13 6665本文给出100道Java编程练手的程序。 列表如下: 面 ... -
数组复制的三种方法
2014-11-30 12:57 2172本文将给出三种实现数组复制的方法 (以复制整数数组为例)。 ... -
数组复制的三种方法
2014-11-30 12:54 0本文将给出三种实现数组复制的方法 (以复制整数数组为例)。 ... -
四种复制文件的方法
2014-11-29 13:21 1679尽管Java提供了一个类ava.io.File用于文件的操 ... -
判断一个字符串中的字符是否都只出现一次
2014-11-25 12:58 2649本篇博文将给大家带来几个判断一个字符串中的字符是否都只出现一 ... -
使用正则表达式判断一个数是否为素数
2014-11-23 13:35 2097正则表达式能够用于判断一个数是否为素数,这个以前完全没有想过 ... -
几个可以用英文单词表达的正则表达式
2014-11-21 13:12 3692本文,我们将来看一下几个可以用英文单词表达的正则表达式。这些 ... -
(广度优先搜索)打印所有可能的括号组合
2014-11-20 11:58 1911问题:给定一个正整n,作为括号的对数,输出所有括号可能 ... -
随机产生由特殊字符,大小写字母以及数字组成的字符串,且每种字符都至少出现一次
2014-11-19 14:48 3933题目:随机产生字符串,字符串中的字符只能由特殊字符 (! ... -
找出1到n缺失的一个数
2014-11-18 12:57 3109题目:Problem description: You h ... -
EnumSet的几个例子
2014-11-14 16:24 8702EnumSet 是一个与枚举类型一起使用的专用 Set 实现 ... -
给定两个有序数组和一个指定的sum值,从两个数组中各找一个数使得这两个数的和与指定的sum值相差最小
2014-11-12 11:24 3280题目:给定两个有序数组和一个指定的sum值,从两个数组 ... -
Java面试编程题练手
2014-11-04 22:49 6647面试编程 写一个程序,去除有序数组中的重复数字 编 ... -
Collections用法整理
2014-10-22 20:55 9793Collections (java.util.Collect ... -
The Code Sample 代码实例 个人博客开通
2014-09-04 18:48 1363个人博客小站开通 http://thecodesample. ... -
Collections.emptyXXX方法
2014-06-08 13:37 2099从JDK 1.5开始, Collections集合工具类中预先 ... -
这代码怎么就打印出"hello world"了呢?
2014-06-08 00:37 7352for (long l = 4946144450195624L ... -
最短时间过桥
2014-04-21 22:03 4067本文用代码实现最短时间过桥,并且打印如下两个例子的最小过桥时间 ... -
将数组分割成差值最小的子集
2014-04-20 22:34 2835本文使用位掩码实现一个功能 ==》将数组分割成差值最小的子集 ...
相关推荐
本文主要对Arrays.asList方法进行总结。具有很好的参考价值,下面跟着小编一起来看下吧
Arrays.asList、ArrayList的subList坑
本文主要介绍了Arrays.asList()方法的使用。具有很好的参考价值,下面跟着小编一起来看下吧
主要介绍了Java Arrays.asList使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
主要介绍了Java中Arrays.asList()方法将数组作为列表时的一些差异的相关资料,需要的朋友可以参考下
在本篇文章里小编给大家分享的是关于Java中使用Arrays.asList初始化ArrayList的知识点内容,需要的朋友们参考下。
下面小编就为大家带来一篇Arrays.asList() 和ArrayList类型区别。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
主要介绍了java 源码分析Arrays.asList方法详解的相关资料,需要的朋友可以参考下
而一开始asList()的设计时用于打印数组而设计的,但jdk1.5开始,有了另一个比较更方便的打印函数Arrays.toString(),于是打印不再使用as
主要给大家介绍了关于为什么说千万别这样使用Arrays.asList()的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
个人研究所得,包含对其内部jdk源码的分析。 同时会结合ArrayList中对该两个方法的调用做进一步说明。...总结一句话:在允许的情况下,尽量调用System.arraycopy方法,实在不行再调用Arrays.copyOf方法。
当我们在实际业务开发过程中,难免会遇到数组转List的操作,通常我们所选择的就是上面的Arrays.asList进行操作,但是,对的但是来了,我们在使用的时候会发现基本数据类型的参数转化的结果会和我们想要的结果完全不...
Apress.PHP.Arrays.Single.Multi-dimensional.Associative.and.Object.Arrays.in.PHP.7.1484225554.rar 最新书籍,精讲PHP数组,文字版PDF
Arduino项目开发 Control_Arrays_Arrays.pdf Arduino项目开发 Control_Arrays_Arrays.pdf Arduino项目开发 Control_Arrays_Arrays.pdf Arduino项目开发 Control_Arrays_Arrays.pdf Arduino项目开发 Control_Arrays_...
Gain an in-depth understanding of PHP 7 arrays. After a quick overview of PHP 7, each chapter concentrates on single, multi-dimensional, associative, and object arrays. PHP Arrays is a first of its ...
Antenna Arrays.pdf
NULL 博文链接:https://128kj.iteye.com/blog/1747459
网络图片地址url集合arrays.xml文件
主要介绍了Java Arrays.sort和Collections.sort排序实现原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
主要介绍了JAVA基于Arrays.sort()实现数组升序和降序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下