Java中有一个类名为AbstractMap.SimpleEntry的数据结构,它可以看作是相当于C++中的std::pairAbstractMap.SimpleEntryMap.Entry接口的实现类,表示一个键值对。它有两个属性:keyvalue

例如:

import java.util.AbstractMap;

public class Main {
    public static void main(String[] args) {
        AbstractMap.SimpleEntry<String, Integer> pair1 = new AbstractMap.SimpleEntry<>("apple", 3);
        AbstractMap.SimpleEntry<String, Integer> pair2 = new AbstractMap.SimpleEntry<>("banana", 2);

        System.out.println(pair1.getKey() + " : " + pair1.getValue());
        System.out.println(pair2.getKey() + " : " + pair2.getValue());
    }
}

输出:

apple : 3
banana : 2

除了AbstractMap.SimpleEntry,还有一个类名为AbstractMap.SimpleImmutableEntry,用法和AbstractMap.SimpleEntry类似,但是它的属性是不可变的

Java有没有相当于stdpairs的数据结构

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

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