Loading topic
String, Integer, or List. The type tells Java which actions are allowed on the value.5 min readList, so every read needs a cast, and a wrong element only fails when the program runs. This chapter fixes that problem. You will write a small class called Box that holds one value, and then make it ge4 min readBox<T>. You may have wondered why the type parameter is called T and not Thing or Item. This chapter explains the naming habits Java programmers follow, why they follow them, and which mistakes a bad name can cause.4 min readBox<T>. A type parameter is a placeholder name for a type. The person using the class fills it in later. Often, though, one placeholder is not enough. A phone book links a name to a number. A score table links a player to point4 min readBox<T> and Pair<K, V>. This chapter uses the same idea for interfaces. You will learn how to declare a generic interface, the main ways a class can implement one, and which generic int4 min readBox<T>. In that class, the type parameter T belongs to the whole class. Sometimes you only need a type parameter for one method, and the class itself does not need to be generic. Generic methods cover that case.4 min readT. That freedom has a cost. If T can be anything, the compiler only knows that T is some kind of Object. You can store it, return it, and print it, but you cannot call methods like compareTo or doubleValue on it.4 min read<T extends Comparable<T>>. Sometimes one bound is not enough. You may need a type that is a number and can also be compared. Java lets you list several bounds at once. This chapter shows how.4 min readInteger is a Number. But a List<Integer> is not a List<Number>. Many beginners find this odd. By the end of the chapter you will know why Java works this way, and you will see the safety problem the rule 4 min readList<Integer> is not a List<Number>, and that List<String> is not a List<Object> either. That rule keeps your lists safe. It also causes a problem. What if you want one method that works with any list, no matter what it holds?4 min readList<Integer> is not a List<Number>. That rule keeps your lists safe, but it also gets in the way. Say you want one method that adds up the numbers in any list of numbers. You would like it to work for a List<Integer>, a List<Double>, and a List<Number>4 min read? extends to read values out of a list. This chapter covers the opposite job: putting values into a list. For that, Java gives you the lower-bounded wildcard, written ? super.4 min read?, ? extends T, and ? super T. Each one makes a method accept more types, and each one also limits what the method can do with its parameter. This chapter gives you one rule for picking the right one. The rule is called PECS.5 min readInteger into a Box<String>. You might expect the running program to know about <String> as well. It does not. This chapter explains why.4 min read@SafeVarargs to tell the compiler it is safe.5 min read