java 入土--集合详解( 三 )


TreeSet<Integer> ts = new TreeSet<Integer>();//自然排序ts.add(10);ts.add(20);ts.add(4);for (Integer i : ts) {System.out.println(i);//输出4,10,20}

java 入土--集合详解

文章插图
通过指定比较器进行排序
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {//o1是o2是的下一个int num = o1.getAge() - o2.getAge();int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;return num2;}});//创建对象Student s1 = new Student("maoyaning", 32);Student s2 = new Student("asdfds", 53);Student s3 = new Student("khljn", 24);Student s4 = new Student("sdfwfds",24);//添加集合元素ts.add(s1);ts.add(s2);ts.add(s3);ts.add(s4);for (Student s : ts) {System.out.println(s.getName() + " " + s.getAge());}Set 两种循环遍历:由于 Set 集合的底层,所以无法用下标遍历,因此只能用增强 for 和 iterator 进行遍历
  1. 增强 for
for (String str : set) {System.out.println(str);}
  1. 迭代器
Set set = new HashSet();Iterator it = set.iterator();while (it.hasNext()) {String str = it.next();System.out.println(str);}Map 接口Map<K,V>,是一个接口,将键映射到值,不能包含重复的键,每个键只能映射一个值 。
java 入土--集合详解

文章插图
Map 接口用于存储具有映射关系的数据,key-value 。
底层:
  • 在创建 Map 集合时,Map 的底层会创建 EntrySet 集合,用于存放 Entry 对象,而一个 Entry 对象具有 key 和 value,同时创建 Set 数组指向 key,创建 collection 对象指向 value,取出时,实际上是调用 set 和 collection 数组的地址进行调用,从而提高遍历效率 。
在进行 map 元素添加时,map.put()方法在底层上是通过 hashcode 与 equals 方法进行比较,当 key 相同时,会进行替换 。要注意的是,HashSet 的底层也是 HashMap,也是以键值对的形式进行存储的,只不过在进行录入时,把 value 值设置为一个常数,所以在 HashSet 中,不能存储相同的值(会进行覆盖) 。而在 Map 中,可以存储相同的 value 值,但是 Key 不能重复,也就是说在 Map 中,key 可以有 null,但是只能有一个,value 可以有多个 null 。
实际开发中,常用 HashMap,TreeMap,LinkedHAshMap,和 HashTable 的子类 properties 。
Map 集合的方法
Map<String, String> map = new HashMap<String, String>();//put方法添加元素map.put("01","maoyaning");map.put("02","guojing");//remove方法删除元素map.remove("01");//clear方法移除所有元素map.clear();//containsKey方法判断是否包含指定的键System.out.println(map.containsKey("01"));//containsValue方法判断是否含有指定的值System.out.println(map.containsValue("maoyaning"));//size返回集合的键值对个数System.out.println(map.size());//isEmpty判断集合是否为空System.out.println(map.isEmpty());Map 集合的获取功能
Map<String, String> map = new HashMap<String, String>();map.put("zhangwuji","01");map.put("asdf","dsf");//get方法,根据键,返回值单个值System.out.println(map.get("zhangwuji"));//keySet获取所有键的集合Set<String> keySet = map.keySet();//获取key的Set集合//增强for循环迭代获取key值for (String key : keySet) {System.out.println(map.get(key));}//values获取所有值的集合Collection<String> values = map.values();for (String value : values) {System.out.println(value);}/**在创建 Map 集合时,Map 的底层会创建 EntrySet 集合,用于存放 Entry 对象,而一个 Entry 对象具有 key 和 value,同时创建 Set 数组指向 key,创建 collection 对象指向 value,取出时,实际上是调用 set 和 collection 数组的地址进行调用,从而提高遍历效率 。*/

经验总结扩展阅读