[英]How does one populate a collection if the types of elements in it are of interface type? (Java)
這是我之前進行的工作面試的一個問題。 我不知道為什么有人會這樣做,或者甚至可能,但是有人會如何填充這個集合?
Collection<MyLinks> links = null; //Populate this variable
public interface MyLinks() {
//Method headers only
}
如果無法實例化MyLinks對象,如何填充此集合? 這是一個技巧問題嗎?
用實現接口的對象填充集合。
public interface MyInterface {
int getANumber();
}
public class RandomNumberGenerator implements MyInterface {
public int getANumber() {
return 4; // choosen by a fair dice roll
}
}
Collection<MyInterface> collection = new ArrayList<MyInterface>();
collection.add(new RandomNumberGenerator());
提示:如果需要隨機數生成器,請不要復制代碼。
這樣的集合可以被其類實現該接口的任何對象填充。 這些對象可以屬於不同的類(甚至是匿名類),只要這些類實現該接口即可。
class ConcreteMyLinks implements MyLinks...
class ConcreteMyLinks2 implements MyLinks...
ConcreteMyLinks obj = new ConcreteMyLinks();
ConcreteMyLinks2 obj2 = new ConcreteMyLinks2();
collection.add(obj);
collection.add(obj2);
collection.add(new MyLinks() { /* implement interface here */ });
您創建一個實現該接口的類,並用它填充它。
試試這個伴侶:
links = new ArrayList<MyLinks>();
links.add(new MyLinks() { });
祝好運!
上面的解決方案是正確的,您還可以使用匿名類:
MyInterface object = new MyInterface() {
//here override interfaces' methods
}
您可以創建實現該接口的具體類的實例,並將其添加到集合中。
collection.add(new MyConcreteLinks());
您可以創建匿名類實例,例如:
collection.add(new MyLinks() { /*overide mylinks method*/});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.