java - How do nested type arguments work? -


why declaration

set<set<string>> var = new hashset<set<string>>(); 

work declaration

set<set<string>> var = new hashset<hashset<string>>(); 

choke?

i'm aware 'top level' (not sure if that's correct phrase here) generics in declaration play different rules inside pointy brackets, i'm interested learn reason. not easy question google, thought i'd try guys.

it's because circumvent type system if allowed. property desire called covariance. if collections covariant you'd able this:

set<set<string>> var = new hashset<hashset<string>>();  var.add(new treeset<string>()); 

a treeset type of set, , static type checking not prevent inserting treeset var. var expects hashsets , hashsets only, not old type of set.

personally, write first declaration:

set<set<string>> var = new hashset<set<string>>(); 

the outer class needs have conrete implementation, there's no need nail down inner class hashset specifically. if create hashset of sets go. whether proceed insert series of hashsets var choice later in program, no need restrict declaration.


for it's worth, arrays in java are covariant, unlike collection classes. code compile , throw runtime exception instead of being caught @ compile time.

// arrays covariant, assignment permitted. object[] array = new string[] {"foo", "bar"};  // runtime exception, can't convert integer string. array[0] = new integer(5); 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -