1.HashSet是Set接口的一个子类,主要的特点是:里面不能存放重复元素,而且采用散列的存储方法,所以没有顺序。这里所说的没有顺序是指:元素插入的顺序与输出的顺序不一致。
public static void main(String[] args) { Set<String> set=new HashSet<String>(); set.add("a"); set.add("b"); set.add("c"); set.add("c"); set.add("d"); //使用Iterator输出集合 Iterator<String> iter=set.iterator(); while(iter.hasNext()) { System.out.print(iter.next()+" "); }
2.ArrayList是List的子类,它和HashSet想法,允许存放重复元素,因此有序。集合中元素被访问的顺序取决于集合的类型。如果对ArrayList进行访问,迭代器将从索引0开始,每迭代一次,索引值加1。然而,如果访问HashSet中的元素,每个元素将会按照某种随机的次序出现。虽然可以确定在迭代过程中能够遍历到集合中的所有元素,但却无法预知元素被访问的次序。
public static void main(String[] args) { List<String> arrList=new ArrayList<String>(); arrList.add("a"); arrList.add("b"); arrList.add("c"); arrList.add("c"); arrList.add("d"); //使用Iterator输出集合 Iterator<String> iter=arrList.iterator(); while(iter.hasNext()) { System.out.print(iter.next()+" "); }
3.HashMap数组的特点是:寻址容易,插入和删除困难;而链表的特点是:寻址困难,插入和删除容易。HashMap 就结合了二者的优点
添加到Map中的数据,与List不一样,是没有顺序的
put方法,可以单次向HashMap中添加一个键值对。
putAll方法,可以把一个HashMap集合对象,整体加入到另外一个HashMap对象中。
注意:两个集合中重复的元素,会被覆盖为新的值。
EntrySet遍历方法,可以得到一个Entry对象的结果集,然后使用Entry对象的getKey和getValue方法。
KeySet遍历方法,先使用keySet函数,获取到HashMap的所有Key的集合对象,然后循环所有的key,通过HashMap的get方法,获取到对应的value。
狄代奇遍历方法 public static void main(String[] args) { Map map=new HashMap(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", "ccc"); map.put("d", "ddd"); Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); System.out.println("map.get(key) is :"+map.get(key)); }