开发者

Only allow specific types in an ArrayList

开发者 https://www.devze.com 2023-04-12 07:07 出处:网络
Is there a way to subclass the ArrayList开发者_Python百科 class to only allow objects of a specific class (or subclass thereof).

Is there a way to subclass the ArrayList开发者_Python百科 class to only allow objects of a specific class (or subclass thereof).

Specifically, I have a base class called RecordStatus and I need to create ArrayLists with objects based on this class.

I know it would be easy to create a class based on ArrayList<RecordStatus> but then, every time I retrieve an element from the array, I need to cast it to the original class.

Is there an easier way to do this?


Is there a way to subclass the ArrayList class to only allow objects of a specific class (or subclass thereof). Specifically, I have a base class called RecordStatus and I need to create ArrayLists with objects based on this class.

That's exactly what the generic construct in Java allows you to do. Note that you don't have to cast the instances coming out of your ArrayList<RecordStatus> as long as all subclasses of RecordStatus have the same API. You only have to do that if the subclasses have different methods/fields. For example, if RecordStatus has a method setStatus, and so does a subclass, no casting is necessary, as the dynamic dispatch of Java's polymorphism will make sure the method that gets implemented is correct based on the type of the instance on which the method is invoked at runtime.


You shouldn't need to cast anything if you set up your types correctly. For example, this should work:

List<RecordStatus> myList = new ArrayList<RecordStatus>();
//Add values to the list
RecordStatus myRecordStatus = myList.get(0);

But if you really want to subclass ArrayList, you can do the following:

private class MyArrayList<R extends RecordStatus> extends ArrayList<R> {
      ...
}


ArrayList<? extends RecordStatus> is as close as you can get.


I've created arrayList without troubles using a line like this

List<RecordStatus> list = new ArrayList<RecordStatus>();


Try Collections.checkedList(List<E> list, Class<E> type). This will ensure the Type-Safety.

0

精彩评论

暂无评论...
验证码 换一张
取 消