2013-02-26 68 views
0

我有一个场景,我想将相同的逻辑应用于不同类型。java中的自定义通用集合修剪类

interface TrimAlgo<T> { 
public List<T> trim(List<T> input); 
} 

class SizeBasedTrim<T> implements TrimAlgo<T> { 
    private final int size; 
    public SizeBasedTrim(int size) { 
     this.size = size; 
    } 

    @Override 
    public List<T> trim(List<T> input) { 
     // check for error conditions, size < input.size etc. 
     return input.subList(0, size); 
    } 
} 

// Will have some other type of TrimAlgo 

class Test { 
    private TrimAlgo<?> trimAlgo; 
    public Test(TrimAlgo<?> trimAlgo) { 
     this.trimAlgo = trimAlgo; 
    } 

    public void callForString() { 
     List<String> testString = new ArrayList<String>(); 
     testString.add("1"); 
     trimAlgo.trim(testString); // Error The method get(List<capture#3-of ?>) in the type TrimAlgo<capture#3-of ?> is not applicable for the arguments (List<String>) 
    } 

    public void callForInt() { 
     // create int list and call trim on it 
    } 
} 

有没有办法做到这一点?请告诉我。谢谢!

+1

有什么问题? – 2013-02-26 12:37:30

+0

'我想在不同的类型中应用相同的逻辑'这是什么意思? – knowbody 2013-02-26 12:38:29

回答

7

在我看来,你需要做的trim()方法通用而不是TrimAlgo类:

interface TrimAlgo { 
    <T> List<T> trim(List<T> input); 
} 

毕竟,它不是像你微调算法本身取决于类型 - 您可以使用相同的实例修剪List<String>List<Integer>

+0

太棒了!谢谢乔恩。还有一个问题,我如何将SizeBasedTrim注入测试? – test123 2013-02-26 12:49:23

+1

@ test123:您只需传入参数即可。参数变为“TrimAlg​​o trimAlg​​o” - 失去泛型。 – 2013-02-26 13:16:38

+0

啊,是的,对不起,您先前的评论确实提到了这一点。再次感谢! – test123 2013-02-26 13:20:46