Chapter 12 Generics and Container Classes
Generic technology can manipulate different types of objects by one type or method while providing type security in translation. Containers (i.e. collections) are a variety of data structures provided in the form of class libraries that users can use directly in programming. Generics can often be used with containers.
12.1 Generics
The essence of generics is to parameterize the types of data and define them by setting type parameters for classes, interfaces, and methods. Generics allow a class or a method to operate on many different types of objects. Using generics means that code written can be referenced by many different types of objects, thereby reducing potential errors caused by data type conversion.For compatibility with existing code, the compiler does not think that i uses generic code with syntax errors, but it compiles with warnings reminding users of the raw type, but the code can still run.
12.1.1 Generic Concepts
Generics are actually defined by adding "type parameters" to classes, interfaces, or methodsImplements the detection of errors at compile time rather than at run time. A generic operates on a data type that is assigned a parameter called a type parameter, so generic refers to parameterizing the type of data. When used in the declaration of classes, interfaces, and methods, this parameter is called a generic class, a generic interface, and a generic method, respectively.An expression is implemented by adding one or more type parameters enclosed in angle brackets to the definition of a general class, interface, and method.". As a general practice, type parameters are expressed in a single capital letter such as T or E. A generic class is defined by adding <T> to the name of a child-ah class, a generic interface by <T> to the name of a child-ah interface, and a generic method is defined by prefixing <T> to the return value type of a method with the following header definitions:
Definition of generic class:
[modifier] class name <T>
Definition of generic interface:
[public] interface interface name <T>
Definition of generic methods:
[public] [static] <T>return value type method name (T parameter)
Once a generic is defined, the type parameter T can be used in code to represent the type of a data rather than the value of the data, that is, T can be considered a type parameter of a generic classAfter you define the type parameters, you can use them directly in each part of the class body or interface you define. Second, when you apply these generic classes or interfaces, you need to specify the actual specific type, that is, to replace the type parameter with the type actual parameter', that is, creating objects with generic classes is replacing each type parameter T within a class with this specific actual type. The actual parameters of a generic must be class types, and the creation of generic classes is called generic objects, a process called instantiation of generics. So the concept of generics is actually giving''Types can also be parameterized like variables, a simple design concept, so generics are also called parametric polymorphisms.
12.1.2 Generic Classes and Their Applications
When creating objects with generic classes, that is, when generic instantiations are used, the specific type of type parameter T can be given according to different requirements. Instead of type conversion, T can be used directly as a type instead of a parameter type or return value type when calling a method of a generic class to pass or return a data type.
//filename:App12_1.java public class App12_1<T> { private T obj; public T getObj() { return obj; } public void setObj(T obj) { this.obj=obj; } public static void main(String[] args) { App12_1<String> name=new App12_1<String>(); App12_1<Integer> age=new App12_1<Integer>(); name.setObj("zhang san"); age.setObj(35); String newName = name.getObj(); int newAge= age.getObj(); System.out.println("name :"+newName); System.out.println("age :"+newAge); } }
.12.1.3 Generic Method
Whether a method is generic or not has nothing to do with whether or not the class it is in is a generic class. To define a generic method, you need to place the generic type parameter before the return value type. Any method in Java, including static methods, can be persisted as a generic method. A generic method, except for its definition, is called as a normal method.
//filename: App12_2.java public class App12_2 { public static void main(String[] args) { Integer[] num= {1,2,3,4,5}; String[] str= {"red","orange","yello","green","purple","vyan"}; App12_2.display(num); App12_2.display(str); } public static <E> void display(E[] list) { for(int i=0;i<list.length;i++) System.out.print(list[i]+" "); System.out.println(); } }
Generally speaking, when writing Java-based methods, the return value type and at least one parameter type should be generic, and the types should be consistent. If only one of the return value types or parameter types uses generics, this generic method is greatly restricted to the same extent that generics are not used.
Note: A static method cannot access the type parameters of a generic class, so if the static method requires generic capabilities, it must be made generic.
When using generic classes, you must specify the actual value of the type parameter when you create a generic object, and when you call a generic method, you don't usually need to specify the type of the parameter, because the compiler has a function called type parameter inference, in which case the compiler adds an extra IWE find the specific type. Type inference is only valid for assignment operations, and it doesn't work in other cases.
12.1.4 Limit the types available for generics
When you define a generic class, you can instantiate a generic class object with any type by default, but in the Java language, you can restrict the data type when you create an object with a generic class. The syntax is as follows:
class ClassName<T extends anyClass>
Where anyClass refers to a class or interface, the statement indicates that "T is a type parameter of the ClassName class, and T has a limitation that either T must be an anyClass class or a subclass that inherits the anyClass class or a class that implements the anyClass interface.
Note: For restricted generics that implement an interface, the extends keyword is also used, not the implements keyword.
12.1.5 Application of generic type wildcards and generic arrays
In addition to the restricted generic classes, the concept of wildcard'?'is introduced in the generic mechanism. It has two main functions: one is to create generic objects that are re-assigned to the class but whose contents cannot be modified, and the other is to restrict the incoming unwanted type arguments in the method's parameters.
Syntax for creating generic class statements:
Generic Class Name<?Extends T> o=null;
Where "? extends T" denotes an unknown subtype of T or T or a class that implements interface T.
12.1.6 Inheriting generic classes and implementing generic interfaces
Classes or interfaces defined as generics can be inherited and implemented.
12.2 Container Class
Container classes are all kinds of data structures that Java can use directly to develop programs in the form of class libraries. The so-called data structures refer to the way data is organized and stored in computers. Data structures can not only store data, but also support operations to access and process it. In object-oriented thinking, a data structure is considered a container.Arrays are a simple data structure. In addition to arrays, Java provides many other data structures in the form of class libraries. These data structures are called container classes or collection classes.
12.2.1 Java Container Framework
There are two interfaces named Collection and Set in the Java program framework. To prevent name conflicts, consider Collection a container and Set a collection.
The Java Container Framework provides ready-made data structures for storing collections of objects, also known as elements.
12.2.2 Collection interface
Collection interface is usually not directly usable, but it provides add elements, delete elements, manage data and methods. 12.2.3 List interface LIst
List Interface LIst is a Collection subinterface. It is a linear table containing ordered elements, in which elements must be stored sequentially, repeatable, and null values can be stored. The order of the elements'homes can be determined by the addition of the elements to the tear race or by the size of the elements.
There are two main implementation list classes: the LinkedList chain list class and the ArraryList array list class. They are both linear tables.
The LinkedList chain table class uses a chain table structure to save objects and a circular double-chain table to implement a List. This structure adds and deletes elements anywhere in the chat table without moving other elements. The size of the chain table can dynamically increase or decrease, but it does not have the random storage feature.
The ArraryList Array List List class uses a one-dimensional array to implement a List, which implements a variable array that allows all elements, including null. It has random access and requires other elements to be moved when inserting or deleting. When there are many elements, insertion and deletion operations are slower.
The principle for choosing these two linear tables is that if you want to access elements randomly from the following table but do not insert or delete them anywhere else except at the end, you should choose the ArraryList class; however, if you want insert or delete operations anywhere in the child-ah linear table, you should choose the LinkedList class.
Grammar:
List list1=new LinkedList();
List list2=new ArraryList();
//filename: App12_7.java import java.util.*; class StringStack { private LinkedList<String> ld=new LinkedList<String>(); public void push(String name) { ld.addFirst(name); } public String pop() { return ld.removeFirst(); } public boolean isEmpty() { return ld.isEmpty(); } } public class App12_7 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); StringStack stack=new StringStack(); System.out.println("Please input data(end with quit)"); while(true) { String input=sc.next(); if(input.equals("quit")) break; stack.push(input); } System.out.println("Last in and First out: "); while(!stack.isEmpty()) System.out.print(stack.pop()+" "); } }
When accessing elements in a container, it is often necessary to access the elements in the container in some order and only once. This is also called iteration. Convenience refers to the subsequent elements that get the current element from the container. There are many ways to traverse the container.
The first is to use the foreach loop structure, which is supported by most containers.
The second is to convert the container object into an array using the toArrary () method defined in the Collection interface, and then use a loop statement to access each element in the array.
The third method is to traverse using the size () and get () methods;
The fourth approach is to take advantage of the iteration capabilities provided by Java.
Iteration is implemented by the Iterable and Iterator interfaces Iterator and ListIterator, which are objects that allow elements within a container to be traversed and optionally deleted. The code for traversing a container using an iterator is as follows;
Iterator it=c.iterator(); while(it.hasNext())_ { Object o=it.next(); ... }
12.2.4 Collection Interface Set
Set is a collection interface without duplicate elements. It inherits from the Collection interface and does not declare any other methods. All its methods are inherited from the Collection interface. Objects in the Set collection are not sorted in a specific way, at least simply by adding objects to the collection, but they must not be duplicated.
1. Hash set HashSet
Hash sets do not use subscripts like linear tables to access the contained elements, but access the elements in the set based on the hash code.
//filename:App12_9.java import java.util.*; public class App12_9 { public static void main(String[] args) { HashSet<String> hs=new HashSet<String>(); for(String a:args) if(!hs.add(a)) System.out.println("element "+a+" is repeated "); System.out.println("the size of this set is "+hs.size()+" , each element is : "); Iterator it=hs.iterator(); while(it.hasNext()) System.out.print(it.next()+" "); } }
2. Tree Collection TreeSet
The TreeSet class of the tree collection implements not only the Set interface, but also the java.util.SortedSet interface.
12.2.5 Mapping Interface Map
Map is another object that stores data structures, and the Map interface is significantly different from the List and Set interfaces.
//filename:App12_11.java import java.util.*; public class App12_11 { public static void main(String[] args) { Map<String,String> hm=new HashMap<String,String>(); hm.put("006", "tang_seng"); hm.put("008", "sun_wu_kong"); hm.put("009", "zhu_ba_jie"); hm.put("007", "sha_he_shang"); hm.put("010", "bai_long_ma"); System.out.println("The content in hashmap is as follows:\n"+hm); String str=(String)hm.remove("010"); Set keys=hm.keySet(); Iterator it=keys.iterator(); System.out.println("disorder map in HashMap class:"); while(it.hasNext()) { String xh=(String)it.next(); String name=(String)hm.get(xh); System.out.println(xh+" "+name); } TreeMap<String,String> tm=new TreeMap<String,String>(); tm.putAll(hm); Iterator iter=hm.keySet().iterator(); System.out.println("ordered map in TreeMap class"); while(iter.hasNext()) { String xh=(String)iter.next(); String name=(String)hm.get(xh); System.out.println(xh+" "+name); } } }