其他分享
首页 > 其他分享> > 集合笔记

集合笔记

作者:互联网

List是一个接口不能实例化,只能实例化其子类 如 List lists = new ArrayList(); (多态的体现)

判断List下是否存在某个元素 list.indexOf("")

判断map下是否存在key map.containsKey("")

判断map下是否存在Value map.containsValue(“”)

遍历集合的三种方式

  1. 转数组
  2. Iterator迭代器 Iterator<String> it = set.iterator(); while(it.hasNext()) {
    String str = it.next();
    System.out.println(str);
    }
  3. 增强for循环

List因为有索引所以多一种普通for循环方式

Map集合的两种遍历方式

Map的第一种遍历方式:

Map的第二种遍历方式:

public class aa {
    public static void main(String[] args) {
        // 创建Map对象
        Map<String, String> map = new HashMap<String, String>();
        // 添加映射关系
        map.put("谢婷疯", "张箔纸");
        map.put("陈关西", "钟欣桶");
        map.put("李亚碰", "王飞");
        method01(map);
        method02(map);
    }
    /*
     *     Map的第二种遍历方式:
     *         通过结婚证对象来获取丈夫和媳妇
     */
    private static void method02(Map<String, String> map) {
        // 获取所有的结婚证对象
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        // 遍历包含了结婚证对象的集合
        for (Map.Entry<String, String> entry : entrys) {
            // 获取每个单独的结婚证对象
            // 通过结婚证对象获取丈夫和媳妇
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("丈夫:" + key + "---" + "媳妇:" + value);
        }
    }
    /*
     *     Map的第一种遍历方式:
     *             首先召集所有的丈夫
     *             遍历所有的丈夫
     *             获取每一个丈夫
     *             让每一个丈夫去找他自己的媳妇
     */
    private static void method01(Map<String, String> map) {
        // 遍历Map对象
        // 首先召集所有的丈夫
        Set<String> keys = map.keySet();
        // 遍历所有的丈夫
        for (String key : keys) {
            // 让每个丈夫去找他自己的媳妇就可以了
            String value = map.get(key);
            System.out.println("丈夫:" + key + "---" + "媳妇:" + value);
        }
    }
}

标签:map,遍历,String,Map,笔记,丈夫,key,集合
来源: https://www.cnblogs.com/RickQi/p/ji-he-biji.html