0

I'm trying to understand the type inference and the use of diamond operator.

Assuming that RaceCar is a subclass of Car, which is a subclass of Vehicle what kind of objects can be added to the following collection?

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

I found What is the point of the diamond operator in Java 7? question, but still don't get it.

Thank you in advance!

LE: it's important to know how inheritance works in this case

Community
  • 1
  • 1
Zodrak
  • 49
  • 1
  • 15
  • The diamond operator is just syntactic sugar for typing whatever's in the left hand set of angle brackets. So in this case, it's exactly the same as `List list = new ArrayList();` – awksp May 30 '14 at 19:23

2 Answers2

2

You can add Car or any subclass of Car. No superclass of Car though.

Edit: As @HotLicks mentioned, you can technically add an object of any type to the List, if you use subterfuge, by casting. Note that this is an easy way to confuse the hell out of yourself though, because you will be pulling an object out of your List and it will have an unexpected type.

import java.util.*;

class Foo{}
class Bar extends Foo{}
class Z{}
public class FooBar2{ 
    public static void main(String[] args) {
        List<Foo> list = new ArrayList<>();
        list.add(new Foo());
        list.add(new Bar());

        // Compile error
//        list.add(new Z());

        // Subterfuge
        ((List) list).add(new Z());
    }
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

The diamond operator is just a syntax simplification improvement that come with new feature of Java 7 ,

in Java 6 we write :

Map<City, Set<Person>> group=new HashMap<City, Set<Person>>();

but in java 7 we can just write ;

Map<City, Set<Person>> group=new HashMap<>();

for the question 'what kind of objects can be added to the following collection' you can add any subclass of the class Car , RaceCar for example.

Mifmif
  • 3,132
  • 18
  • 23