泛型和容器(1)——Collection接口和容器的打印

    java实用类库提供了一套相当完整的容器类,其中基本的类型有List、Set、Queue、和Map,这些对象类型也称为集合类。

    基本概念
    java容器类库的用途是“保存对象”,并将其划分为两个不同的概念:
    (1)Collection。一个独立元素的序列,这些元素都服从一条或多条规则。List必须按照插入的顺序保存元素,而Set不能有重复元素。Queue按照排队规则来确定对象产生的顺序。
    (2)Map。一组成对的“键值对”对象,允许你使用键来查找值。Map是强大的编程工具。

Collection接口存放一组对象的方式:

//简单的collection public class SimpleCollection { public static void main(String[] args) { Collection<Integer> c = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) c.add(i); for (Integer a : c) System.out.print(a + " "); } }

运行结果:

0 1 2 3 4 5 6 7 8 9

add()方法的名称就表明它是要将一个新元素放置到Collection中。

添加一组元素(addAll()方法)

//添加一组元素 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); // collection.addAll()成员方法只能接收一个Collection对象作为参数,因此不如Arrays.asList()或Collection.addAll()灵活 } }

运行结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10]

collection.addAll()成员方法只能接收一个Collection对象作为参数,因此不如Arrays.asList()或Collection.addAll()灵活,这两个方法使用的都是可变参数列表。

容器的打印:
你必须使用Arrays.toString()来产生数组的可打印表示,但是打印容器无需任何帮助

//容器的打印 public class PrintingContainers { static Collection fill(Collection<String> collection) { collection.add("rat"); collection.add("cat"); collection.add("dog"); collection.add("dog"); return collection; } static Map fill(Map<String, String> map) { map.put("rat", "Fuzzy"); map.put("cat", "Rags"); map.put("dog", "Bosco"); map.put("dog", "Spot"); return map; } public static void main(String[] args) { System.out.println(fill(new ArrayList<String>())); System.out.println(fill(new LinkedList<String>())); System.out.println(fill(new HashSet<String>())); System.out.println(fill(new TreeSet<String>())); System.out.println(fill(new LinkedHashSet<String>())); System.out.println(fill(new HashMap<String, String>())); System.out.println(fill(new TreeMap<String, String>())); System.out.println(fill(new LinkedHashMap<String, String>())); } }

运行结果:

[rat, cat, dog, dog] [rat, cat, dog, dog] [cat, dog, rat] [cat, dog, rat] [rat, cat, dog] {cat=Rags, dog=Spot, rat=Fuzzy} {cat=Rags, dog=Spot, rat=Fuzzy} {rat=Fuzzy, cat=Rags, dog=Spot}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值