首页后端开发JAVAjava怎样保存键和值

java怎样保存键和值

时间2023-10-27 07:47:04发布访客分类JAVA浏览458
导读:在Java中,我们经常需要保存一些数据,其中一种常见的需求是保存键和值的关系,例如用于查询和快速访问数据。Java提供了多种方式来实现这一需求,如下:// 使用Map保存键值对Map<String, Integer> map =...

在Java中,我们经常需要保存一些数据,其中一种常见的需求是保存键和值的关系,例如用于查询和快速访问数据。Java提供了多种方式来实现这一需求,如下:

// 使用Map保存键值对MapString, Integer>
     map = new HashMap>
    ();
    map.put("key1", 1);
    map.put("key2", 2);
    map.put("key3", 3);
    System.out.println(map.get("key2"));
     // 输出 2// 使用Hashtable保存键值对HashtableString, Integer>
     table = new Hashtable>
    ();
    table.put("key1", 1);
    table.put("key2", 2);
    table.put("key3", 3);
    System.out.println(table.get("key3"));
     // 输出 3// 使用Properties保存键值对Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream("config.properties")) {
    properties.load(inputStream);
    System.out.println(properties.getProperty("key"));
 // 输出 value}
 catch (IOException e) {
    e.printStackTrace();
}
    // 使用ConcurrentMap保存键值对(线程安全)ConcurrentMapString, Integer>
     concurrentMap = new ConcurrentHashMap>
    ();
    concurrentMap.put("key1", 1);
    concurrentMap.put("key2", 2);
    concurrentMap.put("key3", 3);
    System.out.println(concurrentMap.get("key1"));
 // 输出 1// 使用EnumMap保存键值对(使用枚举作为键)enum Key {
 KEY1, KEY2, KEY3 }
    ;
    EnumMapKey, Integer>
     enumMap = new EnumMap>
    (Key.class);
    enumMap.put(Key.KEY1, 1);
    enumMap.put(Key.KEY2, 2);
    enumMap.put(Key.KEY3, 3);
    System.out.println(enumMap.get(Key.KEY2));
     // 输出 2

以上代码示例中,我们使用了不同的实现方式来保存键值对。其中,Map是用于一般需求的最常用方式,而ConcurrentMap能够保证线程安全;Hashtable和Properties虽然不如Map灵活,但在特定场合下仍然有用武之地;EnumMap则用于将枚举类型映射到其他类型。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: java怎样保存键和值
本文地址: https://pptw.com/jishu/512785.html
js加密 php解密 java成员属性和属性的定义

游客 回复需填写必要信息