我正在使用许多LinkedHashMap
,它们可能是LinkedHashMap<Long, Long>
、LinkedHashMap<Long, Double>
或LinkedHashMap<Long, Integer>
。
我的目标是查找或创建一个方法,以在相同顺序中返回上述LinkedHashMap<Long,...>
中的所有键的List<Long>
。顺序很重要,这就是为什么我认为我不能使用myMap.keySet()
,因为它是一个Set<Long>
。此外,我有许多其他只接受List<Long>
作为输入的方法,因此我希望所需的方法返回该对象类型,以便我可以继续使用这些方法。
编写一个方法来返回例如LinkedHashMap<Long, Long>
就很容易了:
private static List<Long> getLongKeys(LinkedHashMap<Long, Long> target) {
List<Long> keys = new ArrayList<Long>();
for(Map.Entry<Long, Long> t : target.entrySet()) {
keys.add(t.getKey());
}
return keys;
}
然而,我需要写几乎相同的方法,只是用LinkedHashMap<Long, Double>
和LinkedHashMap<Long, Integer>
替换其中一个。
有没有办法将我粘贴的方法泛化,以接受这三种类型:LinkedHashMap<Long, Long>
、LinkedHashMap<Long, Double>
或LinkedHashMap<Long, Integer>
?