大家好,大家好
我对此主题进行了研究,我知道它写在某个地方,但我找不到它(但是我知道我几周前就读到了它)...所以这是我的问题:
使用Java 8,应该可以将接口用作数组或列表中的集合类型(不确定哪个)。...是谁能告诉我此功能的名称是?给我一个抽象或清晰的代码示例?
据我所记得的例子是:您有不同类型的对象,它们都共享相同的接口。使用此接口,可以创建可以存储不同对象类型的列表或数组。
如果有人可以帮助我,我将非常高兴...我真的很喜欢我在那里读到的内容,但是现在我有一些业余时间,无法找到从何处获得这些信息。
先感谢您!
// edit:感谢您的快速回答,realSkeptic!
我想您可能正在考虑自版本5开始使用Java的泛型。假设您有一个名为MyInterface的接口,以及实现该接口的许多类,例如MyClassOne和MyClassTwo。可以创建一个将接受任何实现MyInterface的类的集合(例如List),如下所示:
List<MyInterface> theList = new ArrayList<MyInterface>();
然后,您可以像这样将其添加到列表中:
theList.add(new MyClassOne());
theList.add(new MyClassTwo());
以下将产生编译错误:
theList.add("A String");
从列表返回的对象将是MyInterfaces。您不会立即知道它是MyClassOne还是MyClassTwo:
MyInterface obj = theList.get(0);
if (obj instanceof MyClassOne) {
System.out.println("It's MyClassOne");
} else if (obj instanceof MyClassTwo) {
System.out.println("It's MyClassTwo");
}
对于数组来说,情况与此类似-任何MyInterface实现类都可以加入,而MyInterface实例可以出现:
MyInterface[] array = { new MyClassOne(), new MyClassTwo() };
MyInterface obj = array[0];
if (obj instanceof MyClassOne) {
System.out.println("It's MyClassOne");
} else if (obj instanceof MyClassTwo) {
System.out.println("It's MyClassTwo");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句