java - What is the difference between raw types and generic types in this declaration -


this question has answer here:

what difference between raw types , generic types in declaration

list<integer> list1 = new arraylist<>();  list<integer> list2 = new arraylist(); 

for these declaration can't do

list1.add("hello"); list2.add("hello"); 

so difference

on other word benefit of angle brackets in first declaration

when arraylist<>(), type in angle brackets inferred declaration, resolves arraylist<integer> @ compile time.

if omit angle brackets, assignment uses raw type, i.e. collection type without information of element type. no type inference done compiler assignment.

both lines not compile:

list1.add("hello") list2.add("hello") 

because both list1 , list2 variables declared arraylist<string>.

the point of specifying <> assignment of arraylist() arraylist<string> should generate compiler warning of unchecked assignment, because compiler can't verify raw typed collection right of = sign contains integers. in simple case such yours, can control correctness of code visually. consider more complex scenario:

arraylist rawlist = new arraylist(); rawlist.add("one");  arraylist<integer> list = rawlist; 

here break generic system assigning raw list contains string typed list variable should contain integers. that's compiler warning of unchecked assignment comes in handy.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -