首页 > 解决方案 > 具有 2 个值的循环集合

问题描述

Java 中是否有一些集合,我可以在其中放置 2 个对象,然后通过调用其中一个对象的方法来返回另一个对象?示例:myColection [{o1},{o2}] myCollection.getNext(o1) 以返回 o2,反之亦然。

标签: java

解决方案


使用地图怎么样?

public static <T> Map<T, T> alternate(T s1, T s2)
{
    Map<T, T> map = new HashMap<>();
    map.put(s1,  s2);
    map.put(s2,  s1);
    return map;
}

public static void main(String[] args)
{
    Map<String, String> map = alternate("hello", "world");

    System.out.println(map.get("hello"));
    System.out.println(map.get("world"));
}

推荐阅读