开发者

ArrayList(Collection<? extends E> c)

开发者 https://www.devze.com 2023-01-28 22:48 出处:网络
I know t开发者_运维问答hat in order to create an object of ArrayList type I need to: ArrayList<MyType> l = new ArrayList<MyType>();

I know t开发者_运维问答hat in order to create an object of ArrayList type I need to:

ArrayList<MyType> l = new ArrayList<MyType>();

I know it because I've seen this in books.

But looking at Java SE API for the ArrayList constructor I see: ArrayList(Collection<? extends E> c)

I don't understand, how would I ever get an idea to specify the type of objects my new ArrayList object would hold? How would I know from this definition that I have to specify <MyType> during instantiation and variable declaration?


That method is meant to copy an existing collection instance to the new ArrayList not to create on from scratch. The elements of the collection it will accept have an upper bound of type E which will be the type of your new ArrayList then.


In order to find out if you need type parameters in your declaration, you don't look at the constructor, you look at the class definition itself. The arguments of the constructors have nothing to do with the type of the object itself - a constructor can take any kind of arguments, just like any other method. Here's the class definition:

public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

The class ArrayList<E> part says that there is a class called ArrayList and it requires one type parameter (which is called E here).


Let's say you have a set of shape classes. The base class is Shape, and the two implementations are Square and Circle. Now, after you've done some specific setup for the list of objects you wanted, you need to add it all together to send it to a rendering function. The code below should make what I'm describing a little more clear:

ArrayList<Square> squares = readSquares();
ArrayList<Circle> circles = readCircles();

ArrayList<Shape> queue= new ArrayList<Shape>(squares);
queue.addAll(circles);

renderShapes(queue);

The ArrayList(Collection<? extends E> c) constructor makes line five possible. With generics, the processor is not smart enough to automatically determine that Square extends Shape by default. You have to tell the compiler that is what you intended. The way you do that is with the wildcard <? extends E>. Now the compiler will make sure that every object added is at least a Shape.


That's always true when you construct an object for a class that takes a generic type. If you scroll up to the top, you'll see Class ArrayList< E >. That's the hint.

0

精彩评论

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