2014-02-21 59 views
-4

接口你可以使用一個接口作爲ArrayList的類型嗎?

public interface Inter 
{ 
} 

是否有可能這是因爲做了,我該ArrayList中放置的對象不共享同一個父類,但是,他們都有着相同的接口。

在我的主要方法

List<Inter> inventory = new ArrayList<Inter>(); 
+5

爲什麼不問這個問題之前,先試試這個? –

回答

2

這是絕對有可能的對象,而這將讓你在同一List混合的Inter不同的實現方式:

public class InterImplOne implements Inter { 
    ... 
} 
public class InterImplTwo implements Inter { 
    ... 
} ... 
List<Inter> inventory = new ArrayList<Inter>(); 
inventory.add(new InterImplOne()); 
inventory.add(new InterImplTwo()); 

當您想要編程到需要不同實現的多個項目的接口時,這非常有用。

2

是的,這是可能的。下一次認真就爲自己嘗試一下。

這種方法往往是非常有用的,正是你正在嘗試做的:存儲共享一個通用的接口

0

總而言之,是的。查看arraylist here的文檔。當你想要有一個ArrayList時,當你遍歷它時,這很有效,所有的對象都有相似的屬性。

正如其他人所說,這是一件好事,只是嘗試。實驗是學習的好方法。

+0

從你的回答中不明顯。他們使用ArrayList的事實是無關緊要的。這是一個泛型的問題。 –

0

是的,你可以使用anonimous內部類實例化列表這樣的成分:

package test.regex; 

import java.util.ArrayList; 

public class TestM { 


    interface C{ 
     public void print(int i); 
    } 

    public TestM() { 

     ArrayList<C> list = new ArrayList<TestM.C>(); 

     for(int i=0; i< 10; i++){ 
      final int aa = i; 
      list.add(new C() { 
       public void print(int a) { 
        System.out.println(Integer.toString(aa + a).toUpperCase()); 
       } 
      }); 
     } 

     for(C c : list){ 
      c.print(12); 
     } 
    } 


    public static void main(String[] args){ 
     new TestM(); 
    } 

} 
相關問題