S
S
SlavaMorg2017-10-12 13:36:25
Java
SlavaMorg, 2017-10-12 13:36:25

Where should one write generics in Java?

What generics are for, I basically understand: to get objects of a specific type, and not of the Object type, when accessing the elements of the collection. I just don’t understand why they need to be written twice: Yes, I know that in java 7 you can get by with a diamond, but I still don’t understand why the type is removed in the creation of the collection. Explain the difference between these two lines:
ArrayList<Shape> list = new ArrayList<Shape>();

ArrayList<Shape> list = new ArrayList<Shape>();
ArrayList list = new ArrayList<Shape>();

Thank you in advance.
PS: No, they didn't ban me on Google, though I can't find the answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2017-10-12
@SlavaMorg

In the first case, you will have an ArrayList typed with the Shape class and you can access the elements as Shape objects.
In the second case, you will also have a typed ArrayList, only it will be typed with the Object class (no matter how you initialized the ArrayList), and if you want to refer to the element as a Shape class, you will have to cast the element to the Shape class.
Well, if it's quite simple.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question