java中map与hashmap的区别

在java中,map和hashmap两者都是键值对的集合,存储的元素都是无序的,和插入的顺序无关。

但是,map是一个接口,而hashmap是实现了map接口的类,根据键的HashCode值来存储数据,访问速度快,不支持线程同步。

示例如下:

import java.util.HashMap;

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

        //定义一个HashMap类的对象
        HashMap<Integer, String> testMap = new HashMap<>();
        //添加值
        testMap.put(1, "a");
        testMap.put(2, "b");
        testMap.put(3, "c");
        testMap.put(4, "d");
        testMap.put(5, "e");
        //输出
        System.out.println(testMap);

    }
}

输出:

{1=a, 2=b, 3=c, 4=d, 5=e}

猜你喜欢

转载自blog.csdn.net/kevinjin2011/article/details/129496655