Java中创建Map对象可以使用HashMap类或者TreeMap类。下面是使用HashMap类创建Map对象的示例代码:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // 创建一个HashMap对象
        Map<String, Integer> map = new HashMap<>();

        // 向map中添加元素
        map.put("apple", 1);
        map.put("banana", 2);
        map.put("orange", 3);

        // 输出map的元素
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

输出结果为:

apple -> 1
banana -> 2
orange -> 3

使用TreeMap类创建Map对象的方式类似,只需要将代码中的HashMap替换为TreeMap即可

java创建map对象

原文地址: http://www.cveoy.top/t/topic/iK8Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录