Test 2 Flashcards
(77 cards)
What happens if I declare a specific type for a list interface
declare a specific type → need to define
many List interfaces, one for each specific type
creates a lot of duplicate code
what happens if I declare a list with elements are simply Object
lose the safety of compile-time type checking (need to cast) cant do anything with the list because it needs to be casted to type
type parameter
a variable that takes a type as its value and
is used to make a generic class or interface more specific
what type is List<E></E>
generic type
List<String></String>
parameterized type
List
raw type
what can you do with Parametrized types
Can declare variables of parameterized types
Can construct objects of parameterized types
Can invoke methods on objects of parameterized types
Can define methods that take or return parameterized types
what can’t raw types do
never declare or instantiate!
what can generics extend
Generic types can extend/implement other generic types
We could not define…
public class MyList<T> implements List<E>
Generic types can extend non-generic types</E></T>
what can non generics extend
Non-generic types can also extend/implement generic types
Invariance
must use the exact type specified
Contravariance
can use a less specific type than declared
Covariance
can use a more specific type than declared
Pros of covariance
more flexible
invariance
more safe (less prone to failing at runtime)
boolean add(E elem) (.add)
adds elem to the end of the List and returns true, if its an element it return false
add(int idx, E elem)
adds elem to the List at index idx
E set(int idx, E elem) (.set)
places the element at index idx in the
List, replacing what was there previously
E get(int idx)
returns the element at index idx in the List
int indexOf(E elem)
returns the index of elem in the List
boolean contains(Object obj)
returns true if obj is in the
List; false otherwise
E remove(int idx)
removes element at index idx from the List
boolean remove(Object obj)
removes obj from the List
if remove could be boolean remove or normal remove what does java go with
removes number at that idx