2016-11-24 50 views
1

提出第一個問題,請理解格式錯誤。用Java中的Integers填充任意集合

在java中,使用流,有可能通過使用Intstream填充一些收藏與整數,

IntStream.range(from,to).boxed().collect(Collectors.toCollection(HashSet::new)); 

在哪裏,如果你有更換HashSet例如ArrayListLinkedList你會簡單地返回指定的集合來代替。

利用這一點,你怎麼能設置在這裏你可以指定所需的採集接口來填充的方法?我正在尋找的是這樣的:

public returnType fillWithInt(Class<?> t, int from, int to){ 
    return IntStream.range(from,to) 
     .boxed() 
     .collect(Collectors.toCollection(t::new)); 
} 

嘗試這個,我得到一個警告:

類(java.lang.ClassLoader的)「在私下接觸」的java.lang.Class 。

我一直在這一整天,不知道該怎麼做。

我還不如說是一個聲明,我在編程很新,所以我可能會解決這個完全錯誤的。如果是這種情況,我希望能夠朝正確的方向推動!

+3

提示:什麼呢['toCollection'](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html# toCollection-java.util.function.Supplier-)期望作爲參數類型? – Holger

+0

@霍爾謝謝,我已經認識到我對供應商的不確定性,我會去學習! –

回答

2

A method reference無法使用類的實例定義,因爲您需要實現目標CollectionSupplier

public <C extends Collection<Integer>> C fillWithInt(Class<C> t, int from, int to) { 
    return IntStream.range(from,to) 
     .boxed() 
     .collect(
      Collectors.toCollection(
       () -> { 
        try { 
         return t.newInstance(); 
        } catch (InstantiationException | IllegalAccessException e) { 
         throw new IllegalArgumentException(e); 
        } 
       } 
      ) 
     ); 
} 

例:

Set<Integer> set = fillWithInt(HashSet.class, 1, 10); 

或者乾脆通過提供Supplier作爲方法的參數,如下:

可以使用反射爲未來做

public <C extends Collection<Integer>> C fillWithInt(Supplier<C> supplier, 
    int from, int to){ 
    return IntStream.range(from,to) 
     .boxed() 
     .collect(Collectors.toCollection(supplier)); 
} 

實施例:

Set<Integer> set = fillWithInt(HashSet::new, 1, 10); 
+1

請注意,它在反射變體中不起作用,因爲您不能擁有'Class >'。 'HashSet.class'的類型是'Class ',指的是原始的'HashSet'類型。這是不可解的,所以我們不再需要Java 8下的它。 – Holger