CS 2110 Lecture 17: Lecture 17 - Generics
Document Summary
Lecture 17 - generics: what are generics. We can look at a similar thing by looking at class arraylist The stuff in the <> is a generic: generics are useful with collections. This is a collection of string objects. Collection c = c. add( hey ) works c. add(1960) won"t work: subtypes and subclasses extend naturally to generic types interface collection {} interface list extends collection {} class linkedlist implements list {} Object[] ao = new object[10]; ao = as will be legal. Only checks the types of the elements of the list, and string is a subclass of object! ao[0] = 2110; No compile-time error, integer is a subclass of object. String s = as[0] won"t have a problem in compile-time either. Linkedlist lo = new linkedlist(); lo = ls; is illegal!!! In this case, linkedlist is not a subclass or subtype of linkedlist We want this type of control: defining methods with generic types.