簡體   English   中英

如何將對象列表轉換為接口列表?

[英]How to convert list of objects to list of interfaces?

我有一些適用於接口的類:

這是界面:

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列表在列表更改時以及使用此列表創建控件模型時動態更新控件。

目標是將此列表傳輸到工作對象,因此我可以在主過程中向列表中添加一些新的cat,並且工作人員將在不重新設置其list屬性的情況下知道它(list是主proc和in中的相同對象工人)。 但是,當我調用worker.setList(cats)它會發出關於期望Orderable但是獲得Cat ...的警報,但是Cat實現了Orderable。 我該如何解決這個問題?

這是主要代碼:

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
}

您需要更改Worker類,以便它接受List<? extends Orderable> 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  
   }
}

如果你只是改變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);

看到:

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

//worker.setList(cats); 
worker.setList( new ArrayList<Orderable>(cats)); //create new collection of interface type based on the elements of the old one
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列表,因為cat實現Orderable,您應該能夠將cat添加到列表中。

注意:這是我很快猜到的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM