简体   繁体   English

可比较泛型的局部变量

[英]Local variable for comparable generic

I'm trying to implement sorting for a generic list of Comparable objects. 我正在尝试为可比较对象的通用列表实现排序。 The problem is that I can't define a local variable for such lists and it leads to code duplicates. 问题是我无法为此类列表定义局部变量,并且导致代码重复。

Basically I need a variable that will maintain a returned value from a method with signature 基本上我需要一个变量,该变量将维护带有签名的方法的返回值
<T extends Comparable<T>> List<Item<T>> getItems(int itemType, Class<T> cl) . <T extends Comparable<T>> List<Item<T>> getItems(int itemType, Class<T> cl)

Here is the code https://ideone.com/mw3K26 . 这是代码https://ideone.com/mw3K26 The goal is to avoid code duplicates on lines 25, 26 and 29, 30. 目的是避免在第25、26和29、30行重复代码。

Is it even possible? 可能吗?

Put assosiations itemType -> Class to Map and use it instead if-else. 将关联itemType -> Class放入Map并使用if-else代替。

private static final Map<Integer, Class<? extends Comparable>> types = new HashMap<>();
static {
    types.put(1, Long.class);
    types.put(2, Date.class);
}

public List<Long> getSortedIds(int itemType) {
    Class<? extends Comparable> clz = types.get(itemType);
    if (clz != null) {
        List<Item> items = (List<Item>)getItems(itemType, clz);
        Collections.sort(items);
        return items.stream().map(it -> it.id).collect(Collectors.toList());
    }
    //...
    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM