在看集合源码的时候发现了一件有趣的事:Java自带的集合间转换
先看一下ArrayList集合源码,发现ArrayList默认有个参数为Collection的构造方法
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
然后再看一下其他的conllection集合,发现都有类似于这个的有参构造,所以集合间的转换就直接在创建对象的时候把集合作为参数添加进去就ok。
例如:HashSet转换为ArrayList:
public static void main(String[] args) {
HashSet<Object> set = new HashSet<>();
set.add("123");
ArrayList<Object> list = new ArrayList<>(set);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
}
除了这种还有个方法addAll,查看源码:
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
代码:
public static void main(String[] args) {
HashSet<Object> set = new HashSet<>();
set.add("123");
ArrayList<Object> list = new ArrayList<>();
list.addAll(set); //就是此行
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
}
最近项目中有遇到HashMap的value转换为ArrayList,顺便贴下代码:
private void set(){
Map map = new HashMap();
map.put("aa","11");
map.put("bb","22");
map.put("cc","33");
ArrayList list = new ArrayList();
list.add(map.values()); //这是把map的value值添加到list的一个位置
list.addAll(map.values()); //这是把map的value值添加到list的多个位置
}
至于为什么map.values()能添加到list中,看下map.values()方法的类型:
Collection<V> values();