i trying understand features of generic class , concrete instances, , features of generic collection.
suppose define generic class: stack<t> i'm trying use way:
stack<string> ts = new stack<>(5); stack<object> = new stack<>(5); = ts // compilation error! so stack<string> not stack<object>.
i got confused when defined generic collection:
set<e> elemnts = new hashset<>(); and noticed can use elements.tostring()! means set<e> elemnts extends object! whats going on here?
so generics in java exactly? mentioned dave, generic types compiler enforcements. exact, @ runtime, generic types not exist anymore. replaced object or upper bound of generic type. process called type erasure. so, generic types exist @ compile-time.
then why can not cast arraylist<string> arraylist<object>? though type parameters stand in relation (string object), generic classes not. let me give simple example. if
arraylist<string> strings = new arraylist<string>(); arraylist<object> objects = strings; would possible, if 1 calls
objects.add(new object()); what should happen? since strings can hold strings, java cannot "put" object list. on other hand, if @ declaration of objects there nothing hinting, should not work. therefore, java not allow conversion between generic classes, if generic types stand in relation.
but generic types not present @ runtime. hustle? should arraylist<string> not arraylist<object> @ runtime , therefore, of should not matter? no. since know type @ compile-time, can use contracts. example, when retreiving element out of arraylist<string> 1 can sure retrieved object has public char charat(int) method (since string has method). if, whatever reason, arraylist<string> return object instead of string, 1 not call charat(int) method.
Comments
Post a Comment