Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 可以使用接口作为ArrayList的类型吗?_Java - Fatal编程技术网

Java 可以使用接口作为ArrayList的类型吗?

Java 可以使用接口作为ArrayList的类型吗?,java,Java,接口 public interface Inter { } 是否可以这样做,因为我放置在ArrayList中的对象不共享相同的父类,但它们都共享相同的接口 在我的主要方法中 List<Inter> inventory = new ArrayList<Inter>(); List inventory=new ArrayList(); 是,这是可能的。下一次认真地为自己尝试一下 这种方法通常非常适用于您正试图执行的操作:存储共享一个公共接口的对象这是绝对可能的,它将允许您

接口

public interface Inter
{
}
是否可以这样做,因为我放置在ArrayList中的对象不共享相同的父类,但它们都共享相同的接口

在我的主要方法中

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

是,这是可能的。下一次认真地为自己尝试一下


这种方法通常非常适用于您正试图执行的操作:存储共享一个公共接口的对象这是绝对可能的,它将允许您在同一个
列表中混合
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());
公共类InterImplOne实现Inter{
...
}
公共类interimple两个实现Inter{
...
}    ...
列表清单=新的ArrayList();
inventory.add(新的InterImplOne());
inventory.add(新的interimptwo());

当您想要编程到需要不同实现的多个项目的接口时,这非常有用。

总之,是的。查看arraylist的文档。当您希望拥有一个arraylist,并且当您在其上迭代时,所有对象都具有相似的属性时,这种方法非常有效


正如其他人所说,这是一件值得尝试的好事。实验是一种很好的学习方法。

是的,您可以使用一个匿名的内部类来实例化该列表的组件,如下所示:

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(); 
    }

}
package test.regex;
导入java.util.ArrayList;
公共类TestM{
接口C{
公开作废印刷(int i);
}
公共TestM(){
ArrayList=新建ArrayList();
对于(int i=0;i<10;i++){
最终int aa=i;
list.add(新的C(){
公开作废打印(INTA){
System.out.println(Integer.toString(aa+a.toUpperCase());
}
}); 
}
对于(C:列表){
c、 印刷品(12);
}
}
公共静态void main(字符串[]args){
新TestM();
}
}

在问这个问题之前,为什么不先尝试一下呢?从你的回答来看,这并不明显。他们正在使用ArrayList这一事实与此无关。这是一个泛型的问题。