java基础学习19(Map Collections Arrays)

-------------| Map 如果是实现了Map接口的集合类,具备的特点: 存储的数据都是以键值对的形式存在的,键不可重复,值可以重复
----------------| HashMap 底层也是基于哈希表实现 的。
----------------| TreeMap TreeMap也是基于红黑树(二叉树)数据结构实现 的, 特点:会对元素的键进行排序存储。
----------------| Hashtable 底层也是依赖了哈希表实现的,也就是实现方式与HashMap是一样的,但是Hashtable是线程安全的,操作效率低。

Map

Map的常用函数

在这里插入图片描述

public class Test {
    public static void main(String[] args) {

        Map<String,Object> m = new HashMap<String,Object>();
        m.put("1","阿伟");
        m.put("2","errorCode");

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("1","阿建");
        map.putAll(m);
//        map.remove("2");
//        map.clear();

        System.out.println(map.containsKey("1"));
        System.out.println(map.containsValue("阿伟"));

        Set<Map.Entry<String, Object>> entries = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            System.out.println(next.getKey()+"---"+next.getValue());
        }

    }
}    

Map的遍历方式

这里不过多描述,可以看代码,常说Map有多少多少遍历方式个人觉得了解就行,遍历的方式太多会用就行全部记住干嘛呢。

public class Test {
    public static void main(String[] args) {

        Map<String,Object> m = new HashMap<String,Object>();
        m.put("1","阿伟");
        m.put("2","errorCode");

        //keySet
        Set<String> keySet = m.keySet();
        Iterator<String> iterator1 = keySet.iterator();
        while (iterator1.hasNext()){
            String next = iterator1.next();
            System.out.println(next);
        }

        for (String s:keySet) {
            System.out.println(s);
        }

        Iterator<String> iterator2 = keySet.iterator();
        while (iterator2.hasNext()){
            System.out.println(m.get(iterator2.next()));
        }
        System.out.println("=======================");

        //values
        Collection<Object> values = m.values();
        Iterator<Object> iterator3 = values.iterator();
        while (iterator3.hasNext()){
            System.out.println(iterator3.next());
        }

        for (Object obj :values) {
            System.out.println(obj);
        }
        System.out.println("=======================");


        //entrySet
        Set<Map.Entry<String, Object>> entries = m.entrySet();
        Iterator<Map.Entry<String, Object>> iterator4 = entries.iterator();
        while (iterator4.hasNext()){
            Map.Entry<String, Object> next = iterator4.next();
            System.out.println(next.getKey()+"---"+next.getValue());
        }

        for (Map.Entry<String, Object> map :entries) {
            System.out.println(map.getKey()+"---"+map.getValue());
        }

    }

HashMap

实现原理

首先看下两种情况;
情况一:

class Person{
    private int id;

    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "id:"+this.id+"---name"+this.name;
    }
}

public class Test {
    public static void main(String[] args) {
        Person p1 = new Person(1, "张三");
        Map<Person, String> map = new HashMap<>();
        map.put(p1, "张三");
        map.put(p1, "李四");

        Set<Map.Entry<Person, String>> entries = map.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println(entry.getKey() + "====" + entry.getValue());
        }
		//结果 id:1---name张三====李四
    }
}    

情况二:

class Person{
    private int id;

    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "id:"+this.id+"---name"+this.name;
    }
}

public class Test {
    public static void main(String[] args) {
        Person p1 = new Person(1, "张三");
        Map<Person, String> map = new HashMap<>();
        map.put(new Person(1, "张三") , "张三");
        map.put(new Person(1, "张三"), "李四");

        Set<Map.Entry<Person, String>> entries = map.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println(entry.getKey() + "====" + entry.getValue());
        }
       //id:1---name张三====张三    id:1---name张三====李四
    }
} 

问题分析
这两种情况我们发现第二种情况可以插入两条数据,第一种不行。前文也说了Map种key是不允许重复的,那么当key为引用类型的时候是如何判断key是否重复的呢。在这里插入图片描述
原来如此:
往HashMap添加元素的时候,首先会调用键的hashCode方法得到元素的哈希码值,然后经过运算就可以算出该元素在哈希表中的存储位置。 情况1: 如果算出的位置目前没有任何元素存储,那么该元素可以直接添加到哈希表中。情况2:如果算出的位置目前已经存在其他的元素,那么还会调用该元素的equals方法与这个位置上的元素进行比较,如果equals方法返回 的是false,那么该元素允许被存储,如果equals方法返回的是true,则替换原有数据。

修改代码如下让第二种情况下也只能插入一条数据

class Person{
    private int id;

    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "id:"+this.id+"---name"+this.name;
    }

    @Override
    public int hashCode() {
        return this.getId();
    }

    @Override
    public boolean equals(Object obj) {
        Person p = (Person)obj;
        return p.id == this.id;
    }
}

public class Test {
    public static void main(String[] args) {
        Map<Person, String> map = new HashMap<>();
        map.put(new Person(1, "张三") , "张三");
        map.put(new Person(1, "张三"), "李四");

        Set<Map.Entry<Person, String>> entries = map.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println(entry.getKey() + "====" + entry.getValue());
        }
	 //id:1---name张三====李四
    }

TreeMap

TreeMap 要注意的事项:

  • 往TreeMap添加元素的时候,如果元素的键具备自然顺序,那么就会按照键的自然顺序特性进行排序存储。

  • 往TreeMap添加元素的时候,如果元素的键不具备自然顺序特性, 那么键所属的类必须要实现Comparable接口,把键的比较规则定义在CompareTo方法上,或者在创建TreeMap对象的时候传入比较器。

实现Comparable

class Person implements  Comparable{
    private int id;

    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "id:"+this.id+"---name"+this.name;
    }

    @Override
    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.id-p.id;
    }
}

public class Test {
    public static void main(String[] args) {
        TreeMap<Person,String> treeMap = new TreeMap<Person,String>();
        treeMap.put(new Person(1,"张三"),"张三");
        treeMap.put(new Person(2,"李四"),"李四");

        Set<Map.Entry<Person, String>> entries = treeMap.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println(entry.getKey() + "====" + entry.getValue());
        }
    }
}    

传入比较器

class Person{
    private int id;

    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "id:"+this.id+"---name"+this.name;
    }

    @Override
    public int hashCode() {
        return this.id;
    }
}

class  MyComparator<T> implements Comparator<T>{
    @Override
    public int compare(T o1, T o2) {
        return o1.hashCode()-o2.hashCode();
    }
}
public class Test {
    public static void main(String[] args) {
        TreeMap<Person,String> treeMap = new TreeMap<Person,String>(new MyComparator<Person>());
        treeMap.put(new Person(1,"张三"),"张三");
        treeMap.put(new Person(2,"李四"),"李四");
        treeMap.put(new Person(2,"李四2"),"李四2");
        
        Set<Map.Entry<Person, String>> entries = treeMap.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println("key:"+entry.getKey() + ",====value:" + entry.getValue());
        }
    }
}    

Hashtable

底层也是依赖了哈希表实现的,也就是实现方式与HashMap是一样的,但是Hashtable是线程安全的,操作效率低。

Collections类

  • 对list进行二分查找:前提该集合一定要有序

    • int binarySearch(list,key);
    • binarySearch(list,key,Comparator)
  • 对list集合进行排序

    • sort(list);
    • sort(list,comaprator)
  • 对集合取最大值或者最小值

    • max(Collection)
    • max(Collection,comparator)
    • min(Collection)
    • min(Collection,comparator)
  • 对list集合进行反转

    • reverse(list)
  • 可以将不同步的集合变成同步的集合

    • Set synchronizedSet(Set s)
    • Map synchronizedMap(Map<K,V> m)
    • List synchronizedList(List list)
public class Test {
    public static void main(String[] args) {
        //引用类型
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(21,"张三"));
        list.add(new Person(7,"李四"));
        list.add(new Person(11,"李四"));

        List<String> stringList = new ArrayList<String>();
        stringList.add("7");
        stringList.add("3");
        stringList.add("2");
        stringList.add("12");


        //排序
        Collections.sort(stringList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.hashCode()-o2.hashCode();
            }
        });

        Collections.sort(list,new MyComparator<Person>());

        for (String str:stringList) {
            System.out.println(str);
        }

        for (Person person:list) {
            System.out.println(person);
        }

        //二分查找
        System.out.println(Collections.binarySearch(list,new Person(21,"张三"),new MyComparator<Person>()));
        System.out.println(Collections.binarySearch(stringList, "7", new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.hashCode()-o2.hashCode();
            }
        }));

        //对集合取最大值或者最小值
        System.out.println(Collections.max(stringList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.hashCode()-o2.hashCode();
            }
        }));

        System.out.println(Collections.min(stringList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.hashCode()-o2.hashCode();
            }
        }));

        System.out.println(Collections.max(list,new MyComparator<Person>()));
        System.out.println(Collections.min(list,new MyComparator<Person>()));

        //对list集合进行反转
        Collections.reverse(list);
        for (Person person:list) {
            System.out.println(person);
        }

        //基本类型
        List<Integer> integers = new ArrayList<Integer>();
        integers.add(7);
        integers.add(3);
        integers.add(2);
        integers.add(12);

        Collections.sort(integers);
        for (Integer i:integers) {
            System.out.println(i);
        }
    }
}    

Arrays类

  • 二分查找,数组需要有序
    • binarySearch(int[])
    • binarySearch(double[])
  • 数组排序
    • sort(int[])
    • sort(char[])……
  • 将数组变成字符串: toString(int[])
  • 复制数组: copyOf();
  • 复制部分数组:copyOfRange():
  • 比较两个数组是否相同:equals(int[],int[]);
  • 将数组变成集合:List asList(T[]);
    ① 如果数组中存入的基本数据类型,那么asList会将数组实体作为集合中的元素。
    ② 如果数组中的存入的引用数据类型,那么asList会将数组中的元素作为集合中的元素。
    这样可以通过集合的操作来操作数组中元素,但是不可以使用增删方法,add,remove。因为数组长度是固定的,会出现UnsupportOperationExcetion。
    可以使用的方法:contains,indexOf。
public class Test {
    public static void main(String[] args) {
        //引用类型数组转为集合
        Person peoples[] = new Person[]{new Person(1,"张三"),new Person(2,"李四"),new Person(3,"王二")};
        List<Person> list = Arrays.asList(peoples);
        for (Person p :list) {
            System.out.println(p);
        }

        //基本类型数组转为集合
        Integer is[] = new Integer[]{6,7,8};
        List<Integer> list2 = Arrays.asList(is);
        list2.add(9);
        for (Integer i :list2) {
            System.out.println(i);
        }
    }
}    

附:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值