Reputation:
When declaring a class type variable that points at an instance of a specialized type, the object type is determined by the instantiation rather than the declaration. Example:
Object o = new ArrayList<>();
if(o instanceof ArrayList)
System.out.println("ArrayList it is!");
So, ArrayList can only use the methods and properties of Object, in this case, even if I downcast it. How is it possible for an ArrayList to be only partly implemented, and wouldn't it make more sense if the type was made an Object?
Also, why is it possible to use the diamond inference without having a generic declaration in the first place?
Upvotes: 0
Views: 231
Reputation: 777
Object O = new ArrayList<>();
This particular code says; "Create an reference variable o
of the type Object
and point it to the new ArrayList<>
object created on the heap."
The instanceof
condition is checked when the jvm runs the code. Even if the reference variable is of the type Object
, the actual object that is being created during the execution is the ArrayList
object.
If you try using any of the attributes/methods of the ArrayList<>
using the Object
reference variable o
, e g o.size()
;
The compiler will throw an error.
Upvotes: 1
Reputation: 10729
An empty diamond before Java 7 is a so called raw generic, and effectively it means that the container won't enforce any type constraints about the contained items, besides that they should be an Object. So basically new ArrayList<>();
or new ArrayList();
means new ArrayList<Object>();
. This would basically throw away any type safety what Java generics provide.
@scottb reminded us: Java 7 gave a better usage for empty diamond: with type inference performed by the compiler your code can be a little terser and less error prone. Instead of HashMap<String, Integer> m = new HashMap<String, Integer>();
you can say HashMap<String, Integer> m = new HashMap<>();
.
For the first part: java.lang.Object
is the type you perceive the ArrayList
object if you refer to it using the o
variable. The instanceof
operator doesn't care about what is the type of o
, it will precisely answer your question: is the thing which is "stored behind" the variable o
is really an ArrayList
or not.
Upvotes: 0
Reputation: 1576
If you and I talk over the phone, then you are interfacing with only my voice, but it doesn't mean that the rest of me ceases to exist. You are interfacing with that ArrayList as an Object, but it still has all the parts of an ArrayList - you just aren't interfacing with the other parts.
Upvotes: 2