Collection 集合记录

    技术2022-05-20  57

    * 单值操作接口:Collection、List、Set   |-List、Set是Collection接口的子接口*-对值的操作接口:Map*排序的操作接口:SortedMap、SortedSet*输出的接口:Iterator、ListIterator、Enumeration*队列:Queue

    Collection 集合输出有4种方式   Iterator       --->有迭代接口   ListIterator  ----->双向的输出---可以向前向后输出   foreach  --> 对于数组、集合同样适用   Enumeration ---> 只支持Vector类,古老的输出接口

    Set依靠hashCode和equals()方法区分TreeSet按照Comparable接口指定的规则进行排序Map是保存一对值的集合,所有的内容都是以MapEntry的形式保存的。集合输出要使用Itarator接口,进行迭代输出属性操作使用Properties类完成

    Map 接口保存的内容是一对值 Key,Value常用三个子类---->HashMap,Hashable,TreeMapHashMap--->不能存在重复值,Key不能重复       ---采用异步处理,性能高,非线程安全的操作Hashtable--->与Vector产生时代一样,实现了Map接口  ---采用同步的处理,性能相对较低,线程安全TreeMap---->可以按照KEY的方式进行排序

    给定任意一个类进行排序,必须实现Comparable接口注意一:  Map不能直接使用Iterator输出;在Map中真正保存的还是一个单独的对象,在放入集合里。Interface Map.Entry<k,v>  此接口属于Static声明的接口,还是内部接口 .1.Set<Map Entry<K,V>> entrySet()方法获得Set集合2.通过Set接口为Iterator进行初始化的操作3.通过Iterator取出每一个Map.Entry4.通过Map.Entry进行key与value的分离另用foreach也可以输出注意二:使用非系统类作为Key在Map中可以使用匿名对象找到一个key对应的值Map<String,Person> map = new HashMap<String,Person>();map.get();map.put();

    其他子类IdentityHashMap默认情况下,一个Map集合中key是不能重复的,然而通过这个类加入的内容,如果对象的地址不相等,则认为不是同一个对象,可以重复。(只有在两个对象在执行"=="操作的时候不相等才认为不是两个相同的对象)

    例1.

    package interview.serven.strOrdinal; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class StringCount { public static void main(String[] args) { String str = "abadcdffbaeba"; strCount(str); } private static void strCount(String str) { HashMap map = new HashMap(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { Integer num = (Integer) map.get(ch); if (num == null) num = 1; else num = num + 1; map.put(ch, num); } } Iterator iter = map.keySet().iterator(); StringBuilder sb = new StringBuilder(); while (iter.hasNext()) { Object temp = iter.next(); sb.append(temp.toString()).append(":").append(map.get(temp) + ","); } sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } }

    例2.

    package Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class Testsetmap { public static void main(String[] args) { Map m1 = new HashMap(); Map m2 = new TreeMap(); m1.put("one",new Integer(1)); m1.put("two",new Integer(2)); m1.put("three",new Integer(3)); m2.put("A", new Object[]{3}); m2.put("B", 2); System.out.println(m1.size()); System.out.println(m1.containsKey("one")); System.out.println(m2.containsValue(new Object[]{3})); //对象不相等 System.out.println(m2.containsValue(new Integer(2))); if(m1.containsKey("two")){ int i = ((Integer) m1.get("two")).intValue(); System.out.println(i); } Map m3 = new HashMap(m1); m3.putAll(m2); System.out.println(m3); Iterator iter = m3.keySet().iterator(); while(iter.hasNext()){ Object o = iter.next(); System.out.println(o.toString()+":-->"+m3.get(o)); } } }

     


    最新回复(0)