如何将对象列表转换为接口列表?

43

我有一些与接口相关的类:

这是接口:

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)时,它会提示期望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
}
4个回答

69
你需要修改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  
   }
}

这种方法对我来说效果最好,因为我只需要更改“Worker”方法的签名,而不是声明一个数组,而我不想在所有文件中都触及它。在我看来,这比Matt Ball提出的建议更可行。 - Makibo

12

如果你真的想要一个新的接口类型集合,例如当你没有拥有你调用的方法时。

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

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列表,因为cat实现了Orderable接口,所以您应该能够将cat添加到列表中。

注意:这只是我快速猜测的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接