Testing Generic Methods in Collections Class

This section provides a tutorial example on testing generic methods provided in the java.util.Collections class.

If you want to practice how to use generic methods, you can follow the tutorial example below:

/* CollectionsGenericMethods.java
 - Copyright (c) 2014, HerongYang.com, All Rights Reserved.
import java.util.*;
class CollectionsGenericMethods {
   public static void main(String[] a) {
      java.io.PrintStream o = System.out;
      // Get a List of a single String
      List<String> myList 
         = Collections.<String>singletonList("Java");

      // Get it back as Enumeration of String
      Enumeration<String> myEnum 
         = Collections.<String>enumeration(myList);

      // Convert it as ArrayList of String
      ArrayList<String> myArrayList 
          = Collections.<String>list(myEnum);

      // Add more elements

      // Sort the list

      // Get the minimum element
      String min
         = Collections.<String>min(myArrayList);

      // Find where the minimum is located
      int loc = 
         Collections.<String>binarySearch(myArrayList, min);
      // Show the localtion and value
      o.println("Minimum element, "+min+", is at "+loc);

Compile and run the example, you should see no compilation errors and runtime exceptions. The result seems to be correct:

Minimum element, Bean, is at 0

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

Generic Methods and Type Inference

 What Is a Generic Method?

 Comparing Generic Method with Non-Generic Method

 Non-Generic Method Example - maxNonGeneric()

 Generic Method Example - maxGeneric()

 Generic Methods in java.util.Collections Class

Testing Generic Methods in Collections Class

 What Is Type Argument Inference?

 Type Argument Inference by Parameter List

 Type Argument Inference by Return Value

 Generic Methods using Parameterized Types

 Parameterized Type as Generic Method Return Type

 Lambda Expressions and Method References

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Outdated Tutorials


 PDF Printing Version