Loading topic
List could hold any kind of object. That sounds flexible, but it caused bugs that appeared only while the program was running. Generics fix this. A generic is a class, interface, or method that takes a type as a parameter, so you can say "this is a list of strings" 2 min readList let any object in. The mistake only showed up when the program crashed. A generic class fixes this. It lets the compiler check the types for you.2 min readBox<T>. The T there is a type parameter. A type parameter is a placeholder name for a type that the caller fills in later. Java lets you choose any valid name for it. Most Java code still uses a single capital letter, and each letter usually carries a meaning.2 min readBox<String> box = new Box<String>("hi");. That line names String twice. Java can work out the second one for you. This chapter shows how.2 min readT, that the caller replaces with a real type. Some classes need to hold two or more values of different types, so they need more than one placeholder.2 min readT. It works the same way it does in a generic class. The type gets filled in later, when someone uses the 2 min readBox<T>, gets its type parameter once, when you create an object. Sometimes only one method needs that flexibility. For that case, Java has generic methods.2 min readT can stand for any type. That flexibility has a cost. Inside your code, the compiler knows nothing about T, so you can only call methods that every object has, such as toString(). A bound is a rule that limits which types T may be. In return, you get to use the met1 min read<T extends Comparable<T>>. Sometimes one bound is not enough. You may need a type that is a number and can be compared. Java lets you ask for both at once.2 min readInteger is a Number. Integer is a subclass of Number, so you can store an Integer in a Number variable. It seems natural to expect the same for lists, but Java says no. This chapter explains the reason.2 min readList<Integer> is not a List<Number>. That rule keeps your lists safe, but it can make methods less useful. This chapter shows how ? extends fixes that problem when you only need to read from a list.2 min read? extends let you read from a list safely. Now you will learn the opposite tool. ? super lets you write into a list safely.2 min read? extends T lets you read from a collection. ? super T lets you write to one. This chapter gives you a simple rule for picking the right one each time.2 min readList<String> is just a List. Because of this, some things that look reasonable will not compile. This chapter cov1 min readList<String>. Java still accepts older code written before generics existed. This chapter shows you how to spot that older style and how to understand the warnings the compiler gives you about it.2 min read