java中各种容器类的比较

来源:互联网 发布:用友软件工资模块 编辑:程序博客网 时间:2024/06/05 01:57

1.ArrayList类:

ArrayList容器里面装的对象是按你添加的顺序来排列的,你向容器里面加了什么,它就有什么。并且能根据索引来找出你添加的对象。

2.HashSet类:

HashSet容器装的对象是无序的,并且是唯一的,即容器里面不会出现两个相同的对象。它也不能根据索引来寻找对象。

3.HashMap类:

HashMap容器装的对象是键值对的形式,如:HashMap<key,value> map = new HashMap<key,value>(); key是唯一的,如果在这个容器里放了多个值,但key相同的键值对,那么最后存在的会是最后一个放进去的,前面的都会被覆盖掉。下面举一些实例来说明一下:

import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;public class Text2 {public static void main(String[] args) {ArrayList<String> a = new ArrayList<String>();HashSet<String> b = new HashSet<String>();HashMap<Integer, String> c = new HashMap<Integer, String>();a.add("first");a.add("second");a.add("first");System.out.println(a);   //[first, second, first]System.out.println("--------");b.add("first");b.add("second");b.add("first");System.out.println(b);   //[second, first]System.out.println("--------");c.put(1, "first");c.put(2, "second");c.put(3, "third");c.put(3, "four");System.out.println(c);   //{1=first, 2=second, 3=four}}}
上述代码中的注释即它们的输出结果。

原创粉丝点击