Java 17 Recipes
-5. Safely Enabling Types or Methods to Operate
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
7-5. Safely Enabling Types or Methods to Operate
on Objects of Various Types Problem Your application uses many different object types, and there are containers within your class that are available for holding each of these different types. You are interested in ensuring your application remains bug-free, yet you want to dynamically change the Chapter 7 Data SourCeS anD ColleCtionS 261 type of object a particular container may hold. In other words, you want to define a generic container, but can specify its type each time a new instance of the container is instantiated. Solution Use generic types to decouple the type from the container. Generics are a way to abstract over object types, not explicitly declaring the type of an object or container. All collection types are parameterized to allow you to specify, at the time of instantiation, the type of elements the collection can hold. The following example code demonstrates how to use generics in various scenarios. The comments in the code indicate where the generics are utilized. public class MainClass { static List team; private static void loadTeam() { System.out.println("Loading team..."); // Use of the diamond operator team = new ArrayList<>(); Player player1 = new Player("Josh", "Juneau", 5); Player player2 = new Player("Duke", "Java", 15); Player player3 = new Player("Jonathan", "Gennick", 1); Player player4 = new Player("Bob", "Smith", 18); Player player5 = new Player("Steve", "Adams", 7); team.add(player1); team.add(player2); team.add(player3); team.add(player4); team.add(player5); } public static void main(String[] args) { loadTeam(); Chapter 7 Data SourCeS anD ColleCtionS 262 // Create a list without specifying a type List objectList = new ArrayList(); Object obj1 = "none"; objectList.add(obj1); // Create a List that can be of type that is any superclass of Player (or only Player type itself) List super Player> myTeam = objectList; for (Object p : myTeam) { System.out.println("Printing the objects..."); System.out.println(p.toString()); } // Create a Map of String keys and String values Map strMap.put("first", "Josh"); strMap.put("last", "Juneau"); System.out.println(strMap.values()); } } Note When we generally talk about a collection or a collection type, you can read this as those types that make up the Java collections framework. this includes all the classes and interfaces from the Collection and Map interfaces. Collection types generally refer to types that descend from the Collection interface. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling