這是我早些時候面試的一個問題。我不知道爲什麼有人想要這樣做,或者甚至有可能,但有人會如何填充這個集合?如果一個集合中的元素的類型是接口類型,如何填充集合? (Java)
Collection<MyLinks> links = null; //Populate this variable
public interface MyLinks() {
//Method headers only
}
如果MyLinks對象無法實例化,該如何填充此集合?這是個詭計問題嗎?
這是我早些時候面試的一個問題。我不知道爲什麼有人想要這樣做,或者甚至有可能,但有人會如何填充這個集合?如果一個集合中的元素的類型是接口類型,如何填充集合? (Java)
Collection<MyLinks> links = null; //Populate this variable
public interface MyLinks() {
//Method headers only
}
如果MyLinks對象無法實例化,該如何填充此集合?這是個詭計問題嗎?
這樣的集合可以填充任何類的實現該接口的對象。這些對象可以是不同的類(即使是匿名類),只要這些類實現該接口即可。
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 */ });
您創建了一個實現接口的類,然後用它填充它。
用對象填充集合實現了的接口。
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());
提示:如果您需要隨機數生成器,請不要複製代碼。
試試這個隊友:
links = new ArrayList<MyLinks>();
links.add(new MyLinks() { });
祝你好運!上述
這隻適用於'MyLinks'沒有實現方法... – iamnotmaynard 2013-02-21 20:49:33
正確...因爲在上面的代碼片段中,它不會:)如果它 - 只是在捲曲之間新的MyLinks()之後實現存根括號。 – vikingsteve 2013-02-21 21:23:22
的解決方案是正確的,你也可以使用匿名類:
MyInterface object = new MyInterface() {
//here override interfaces' methods
}
您可以創建一個實現該接口的具體類的實例,並把它添加到收藏 。
collection.add(new MyConcreteLinks());
你可以創建匿名類實例,如:
collection.add(new MyLinks() { /*overide mylinks method*/});
用'null' :) – 2013-02-21 20:45:31
@JigarJoshi填充:嘿。技術上正確,但完全沒用;一個很好的回答,然後再轉向真正的一個。 :-) – BlairHippo 2013-02-21 20:48:27
這不會編譯。爲什麼'public interface MyLinks'後面有括號? – hertzsprung 2013-02-21 20:49:48