2015-07-13 100 views
0

我有一個類型MyType<T>,它包含一個通用類型T。我有一個BlockingQueue<MyType<T>>類型的阻塞隊列。我想發送「流尾」標記到隊列中,即毒丸,但問題是我不能實例化毒丸,因爲它是通用類型的。有沒有解決的辦法?當隊列類型包含通用類型時阻塞隊列

回答

2

您應該可以創建一個。

class MyType<T> { 


    private BlockingQueue<MyType<T>> q = new ArrayBlockingQueue<>(10); 
    // Poison pill to signal the end of the queue. 
    public static final MyType<?> PILL = new MyType<>(); 

    /** 
    * Special private constructor for PILL creation. 
    */ 
    private MyType() { 

    } 

    public boolean queueClosed() { 
     return q.peek() == PILL; 
    } 
} 

如果你有你自己的構造函數,你可以添加一個沒有參數的private構造函數。

+0

這並不工作,因爲對構造函數沒有保證。另外,在MyType的每個實例中存儲一個空對象效率不高。 – Max

+0

@Max - 我注意到我的不是'靜態' - 修正了這個問題。更好? – OldCurmudgeon

0

沒有看到您的代碼,很難找到正確的解決方案。我能想到的是:

  • 將一種方法添加到MyType,表明這是毒丸。

  • 創建一個空PoisonPill標記接口,並添加一個getPoison()靜態方法來MyType返回使用instanceof一個MyType implements PoisonPill然後進行測試。

1

您仍然可以創建通用對象並進行投射。例如看java.util.Collections.emptyList():

@SuppressWarnings("unchecked") 
public static final List EMPTY_LIST = new EmptyList<Object>(); 

@SuppressWarnings("unchecked") 
public static final <T> List<T> emptyList() { 
    return (List<T>) EMPTY_LIST; 
} 

只要確保最終的流標記處理不使用/取決於