如何通过只知道方法的接口类并将其添加到ArrayList来传递实现接口的类的对象?

时间:2017-11-05 15:22:17

标签: java generics arraylist

假设我有一个接口和多个实现此接口的类:

public interface MyInterface {
   public String getString();
   public String getAnotherString();
}

现在我有了实现此接口的类:

public class MyClass1 implements myInterface {
   @Override
   public String getString() {
       return "A String";
   }
   @Override
   public String getAnotherString() {
      return "foo";
   }
}

public class MyClass2 implements myInterface {
    @Override
    public String getString() {
        return "Another String";
    }
    @Override
    public String getAnotherString() {
       return "bar";
    }
}

如何让Method接受实现myInterface的类的对象?

public <T extends MyInterface> void aMethod(T object) {
    objects.add(object); //⚡ doesn't work
}

这样可行,但它不允许我将这些对象添加到我声明的那个ArrayList中:

ArrayList<? extends MyInterface> objects = new ArrayList<>();

我做错了什么? :/

1 个答案:

答案 0 :(得分:0)

根据的泛型?扩展MyInterface 只允许使用getter

ArrayList<? extends MyInterface> objects = new ArrayList<>();
you can only do get of type MyInterface and Object
MyInterface myInterace = objects.get(0);
Object myInterace = objects.get(0);

为了您的工作,您可以使用ArrayList<MyInterface> objects = new ArrayList<>();

现在假设如果允许添加MyInterface hade,那么通过一个简单的例子会发生什么错误

Long longValue = 20L; 
List<Long> longList = new ArrayList();
longList.add(longValue);

Integer i =10;
List<? extends Number> sNumber = longList ;// longList can be assigned to ? extends Number
sNumber.add(i); // if this was allowed
longValue = longList.get(1);   // we will get an exception (class cast exception)

因此编译器不允许该setter