带有实现接口的对象的 ArrayList

ArrayList with Objects which implements an Interface

我想要一个 ArrayList,您可以在其中添加实现接口的对象。 像这样:

ArrayList<Object implements Interface> list =
   new ArrayList<Object which implements a specific Interface>();

正确的语法是什么?

只需将接口设置为泛型类型即可。这是 C# 中的代码:

interface IFoo {
    void foo();
}

class Foo1 : IFoo {
    public void foo() {
        Console.WriteLine("foo1");
    }
}

class Foo2 : IFoo {
    public void foo() {
        Console.WriteLine("foo2");
    }
}

class Program {
    public static void Main() {
        // IFoo type: any object implementing IFoo may go in
        List<IFoo> list = new List<IFoo>();
        list.Add(new Foo1());
        list.Add(new Foo2());
        foreach(IFoo obj in list) obj.foo(); // foo1, foo2
        Console.ReadKey();
    }
}