2011-09-27 96 views
28

我有一些類與接口的工作原理:如何將對象列表轉換爲接口列表?

這裏的接口:

public interface Orderable 
{ 
    int getOrder() 
    void setOrder() 
} 

這裏是工人階級:

public class Worker 
{ 
    private List<Orderable> workingList; 

    public void setList(List<Orderable> value) {this.workingList=value;} 

    public void changePlaces(Orderable o1,Orderable o2) 
    { 
    // implementation that make o1.order=o2.order and vice versa 
    } 
} 

這是一個實現了接口的對象:

public class Cat implements Orderable 
{ 
    private int order; 

    public int getOrder() 
    { 
     return this.order; 
    } 

    public void setOrder(int value) 
    { 
     this.order=value; 
    } 

    public Cat(String name,int order) 
    { 
     this.name=name; 
     this.order=order; 
    } 
} 

在主要過程中,我創建一個列表的貓。我使用glazed lists來動態更新控件,當列表更改時以及使用此列表創建控件模型時。

目標是將這個列表轉移到一個工作對象,所以我可以在主過程的列表中添加一些新的貓,並且工人將會知道它而不再次設置它的列表屬性(列表是同一個對象在主要過程和工人)。但是當我打電話給worker.setList(cats)時,它警告預期可訂購,但獲得Cat ...但Cat實現可訂購。我該如何解決這個問題?

下面是主要代碼:

void main() 
{ 
    EventList<Cat> cats=new BasicEventList<Cat>(); 

    for (int i=0;i<10;i++) 
    { 
     Cat cat=new Cat("Maroo"+i,i); 
     cats.add(cat); 
    } 

    Worker worker=new Worker(); 
    worker.setList(cats); // wrong! 
    // and other very useful code 
} 

回答

32

您需要更改Worker類,以便它接受List<? extends Orderable>

public class Worker 
{ 
    private List<? extends Orderable> workingList; 

    public void setList(List<? extends Orderable> value) {this.workingList=value;} 

    public void changePlaces(Orderable o1,Orderable o2) 
    { 
    // implementation that make o1.order=o2.order and vice verca 
    } 
} 
+0

這種方法的工作最適合我,因爲我只需要改變「工人」的方法簽名,數組,我不想在我的_all_文件碰不聲明。國際海事組織比馬特波爾建議的答案更可行 – Makibo

7

它應該工作,如果你只需要改變的cats聲明:

List<? extends Orderable> cats = new BasicEventList<? extends Orderable>(); 

for (int i=0; i<10; i++) 
{ 
    cats.add(new Cat("Maroo"+i, i)); 
} 

Worker worker = new Worker(); 
worker.setList(cats); 

參見:

1
void main() 
{ 
    EventList<Orderable> cats = new BasicEventList<Orderable>(); 

    for (int i=0;i<10;i++) 
    { 
     Cat cat=new Cat("Maroo"+i,i); 
     cats.add(cat); 
    } 

    Worker worker=new Worker(); 
    worker.setList(cats); // should be fine now! 
    // and other very usefull code 
} 

晴,只是構建Orderables名單馬上,因爲貓實施ents Orderable,你應該可以添加一個貓到列表中。

注:這是我的猜測很快

4

如果你真的想接口類型的一個新的集合。例如,你不擁有你所調用的方法。

//worker.setList(cats); 
worker.setList(new ArrayList<Orderable>(cats)); //create new collection of interface type based on the elements of the old one 
相關問題