读书人

Java容器类学习札记

发布时间: 2012-12-28 10:29:05 作者: rapoo

Java容器类学习笔记

1.容器类添加一组数据

import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.List;public class AddingGroups {public static void main(String[] args) {Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));Integer[] moreInts = {6,7,8,9,10};collection.addAll(Arrays.asList(moreInts));Collections.addAll(collection, 11, 12, 13, 14, 15);Collections.addAll(collection, moreInts);System.out.println("collection");for(Integer i : collection)System.out.print(i + ", ");List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);list.set(1, 99); //modify an elementSystem.out.println();System.out.println("list");for(Integer i : list)System.out.print(i + ", ");//list.add(21);  java.lang.UnsupportedOperationException--Runtime error because the array cannot be resized.}}

?collection.addAll()成员方法只能接受一个Collection对象作为参数,但是它不如Array.asList()或Collections.addAll()灵活,这两个方法使用的是可变参数列表。

j2se_1.6/api写道Collection:
boolean addAll(Collection <? extends E > c)
Adds all of the elements in the specified collection to this collection (optional operation).

Arrays:
static <T> List<T> asList (T... a)
Returns a fixed-size list backed by the specified array.

Collections:
static <T> boolean addAll (Collection <? super T> c, T... elements)
Adds all of the specified elements to the specified collection.

?

读书人网 >编程

热点推荐