Computer Science
Java Generics
Java Generics is a feature that allows developers to write code that can work with different types of objects. It provides a way to create classes, interfaces, and methods that can work with any type of data, without having to specify the type at compile time. This helps to improve code reusability, type safety, and performance.
Written by Perlego with AI-assistance
Related key terms
1 of 5
5 Key excerpts on "Java Generics"
- 18 C H A P T E R 837 GENERIC CLASSES To understand the objective of generic programming To implement generic classes and methods To explain the execution of generic methods in the virtual machine To describe the limitations of generic programming in Java CHAPTER GOALS CHAPTER CONTENTS 18.1 GENERIC CLASSES AND TYPE PARAMETERS 838 18.2 IMPLEMENTING GENERIC TYPES 839 SYN Declaring a Generic Class 840 18.3 GENERIC METHODS 843 SYN Declaring a Generic Method 844 18.4 CONSTRAINING TYPE PARAMETERS 845 CE 1 Genericity and Inheritance 847 CE 2 The Array Store Exception 847 ST 1 Wildcard Types 848 18.5 TYPE ERASURE 849 CE 3 Using Generic Types in a Static Context 852 ST 2 Reflection 852 WE 1 Making a Generic Binary Search Tree Class © Don Bayley/iStockphoto. 838 In the supermarket, a generic product can be sourced from multiple suppliers. In computer science, generic programming involves the design and implementation of data structures and algorithms that work for multiple types. You have already seen the generic ArrayList class that can be used to collect elements of arbitrary types. In this chapter, you will learn how to implement your own generic classes and methods. 18.1 Generic Classes and Type Parameters Generic programming is the creation of programming constructs that can be used with many different types. For example, the Java library programmers who imple-mented the ArrayList class used the technique of generic programming. As a result, you can form array lists that collect elements of different types, such as Array-List , ArrayList , and so on. The LinkedList class that we implemented in Section 16.1 is also an example of generic programming—you can store objects of any class inside a LinkedList . That LinkedList class achieves genericity by using inheritance. It uses references of type Object and is therefore capable of storing objects of any class. For example, you can add elements of type String because the String class extends Object .
- 629 C H A P T E R 18 GENERIC CLASSES C H A P T E R G O A L S To understand the objective of generic programming To implement generic classes and methods To explain the execution of generic methods in the virtual machine To describe the limitations of generic programming in Java C H A P T E R C O N T E N T S © Don Bayley/iStockphoto. 18.1 GENERIC CLASSES AND TYPE PARAMETERS 630 18.2 IMPLEMENTING GENERIC TYPES 631 SYN Declaring a Generic Class 632 18.3 GENERIC METHODS 634 SYN Declaring a Generic Method 635 18.4 CONSTRAINING TYPE PARAMETERS 636 CE 1 Genericity and Inheritance 637 CE 2 The Array Store Exception 638 ST 1 Wildcard Types 638 18.5 TYPE ERASURE 639 CE 3 Using Generic Types in a Static Context 642 ST 2 Reflection 642 WE1 Making a Generic Binary Search Tree Class 643 630 In the supermarket, a generic product can be sourced from multiple suppliers. In computer science, generic programming involves the design and implementation of data structures and algorithms that work for multiple types. You have already seen the generic ArrayList class that can be used to collect elements of arbitrary types. In this chapter, you will learn how to implement your own generic classes and methods. 18.1 Generic Classes and Type Parameters Generic programming is the creation of programming constructs that can be used with many different types. For example, the Java library programmers who imple- mented the ArrayList class used the technique of generic programming. As a result, you can form array lists that collect elements of different types, such as Array- List, ArrayList, and so on. The LinkedList class that we implemented in Section 16.1 is also an example of generic programming—you can store objects of any class inside a LinkedList. That LinkedList class achieves genericity by using inheritance. It uses references of type Object and is therefore capable of storing objects of any class.
- No longer available |Learn more
- Marcin Moskala, Igor Wojda(Authors)
- 2017(Publication Date)
- Packt Publishing(Publisher)
Generics Are Your Friends
In the previous chapter, we discussed concepts related to functional programming and functions as first-class citizens in Kotlin.In this chapter, we will discuss concept of generic types and generic functions known as generics. We will learn why they exist and how to use them--we will define generic classes, interfaces, and functions. We will discuss how to deal with generics at runtime, take look at subtyping relations, and deal with generics nullabilityIn this chapter, we will discuss the concepts of generic types and generic functions, known as generics. We will learn why they exist and how to use them and also how to define generic classes, interfaces, and functions. We will discuss how to deal with generics at runtime, take a look at subtyping relations, and deal with generic nullability.In this chapter, we will cover the following topics:- Generic classes
- Generic interfaces
- Generic functions
- Generic constraints
- Generic nullability
- Variance
- Use-site target versus declaration-site target
- Declaration-site target
- Type erasure
- Reified and erased type parameters
- Star-projection syntax
- Variance
Passage contains an image
Generics
Generic is a programming style where classes, functions, data structures, or algorithms are written in such a way that the exact type can be specified later. In general, generics provide type safety together with the ability to reuse a particular code structure for various data types.Generics are present in both Java and Kotlin. They work in a similar way, but Kotlin offers a few improvements over the Java generic type system, such as use-site variance, start-projection syntax, and reified type parameters. We will discuss them in this chapter.Passage contains an image
The need for generics
Programmers often need a way to specify that a collection contains only elements of particular type, such as Int, Student, or Car. Without generics, we would need separate classes for each data type (IntList, StudentList, CarList, and so on). Those classes would have a very similar internal implementation, which would only differ in the stored data type. This means that we would need to write the same code (such as adding or removing an item from a collection) multiple times and maintain each class separately. This is a lot of work, so before generics were implemented, programmers usually operated on a universal list. This forced them to cast elements each time they were accessed: - eBook - PDF
- Tod Golding(Author)
- 2005(Publication Date)
- Wrox(Publisher)
When I look at an interface, I don’t want there to be any ambiguity about what it accepts or what it returns. There shouldn’t be room for interpretation. Through generics, you are provided with new tools that can make your interfaces much more expressive. And, although this expressiveness makes the syn- tax more verbose and may rarely make your code run faster, it should still represent a significant factor in measuring the quality of your code. As developers get more comfortable with generics, any objections to the syntactic impact of this new language feature are likely to subside. The benefits they bring to your code are simply too significant to be brushed aside simply because they tend to increase the verbosity of your declarations. Summary Type safety is one of the key value propositions of generics. As such, it is vital for you to have a good grasp on how generics can be applied in ways that will enhance the overall type safety of your solutions. The goal of this chapter was to try and expose some of the type-safety compromises developers have been traditionally forced to make and discuss how generics can be employed to remedy these problems. The chapter looked at how types have been required to use least common denominator object types to achieve some level of generality and, in doing so, accept the overhead and safety issues that accompany that approach. As part of exploring these type-safety issues, the chapter also looked at how generics could be applied to eliminate a great deal of these type-safety problems. You also learned how generics bring a new level of expressiveness to your code and how generics can improve the quality and main- tainability of your solutions. Overall, the chapter should give you a real flavor for how generics will influence the expectations you place on the signatures of the types you create and consume. 33 Valuing Type Safety - Available until 4 Dec |Learn more
- Ray Toal, Rachel Rivera, Alexander Schneider, Eileen Choe(Authors)
- 2016(Publication Date)
- Chapman and Hall/CRC(Publisher)
In a stati- cally typed language, it makes sense to use parameterized types to implement these collec- tions. Java calls these generic types, and these are next up on our tour. 7.5 GENERICS As Java tends to favor static typing, parameterized types, known as generic types, appear quite often. Lists and sets provide a typical illustration: Java ■ 131 import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.HashSet; public class ListAndSetExample { public static void main(String[] args) { List words = Arrays.asList("do", "while", "if", "a"); Set sizes = new HashSet<>(); for (String word: words) { sizes.add(word.length()); } assert sizes.equals(new HashSet(Arrays.asList(5,2,1))); } } We’ve created two variables, words of type list-of-strings, and sizes, of type set-of-integers. Both List and Set are interfaces in the package java.util; E is (as we’ve seen in Julia) a type parameter. We’ve initialized sizes with an object of class HashSet 8 (note that the type argument Integer is inferred). The variable words is initialized to an object of some class implementing the list interface; we don’t exactly know, nor care, which class this is—we access the object through the methods defined by the interface type. Java collections are invariant, so a list of cows may not be assigned to a list of animals. In order to write a method that operates on a list of animals, while accepting as an argument a list of sheep or a list of horses, we may use a wildcard (?): import java.util.List; import java.util.Arrays; public class AnimalChorusApp { public static void chorus(List animals) { for (Animal animal : animals) { System.out.println(animal.speak()); } } public static void main(String[] args) { List cows = Arrays.asList(new Cow("Bessie")); List sheep = Arrays.asList(new Sheep("Wooly")); chorus(cows); chorus(sheep); } } Java’s is analogous to Julia’s {T<:Animal}.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.




