SoFunction
Updated on 2025-03-02

Java generic definition and usage examples

This article describes the definition and usage of Java generics. Share it for your reference, as follows:

1. Introducing generic background

Java collections do not know what type of objects they need to use to save, so they design the collection to be able to save any type of objects, only requiring good universality. But doing so also brings two problems:

  • Collections have no restrictions on element types, which may cause some problems: for example, want to create a collection that can only save Dog objects, but programs can also easily "drop" Cat objects, so exceptions may be raised.
  • Since when "dropping" the object into the collection, the collection loses the state information of the object, the collection only knows that it is loaded with an Object, so casting is usually required after taking out the collection elements. This casting can both increase programming complexity and may also raise ClassCastException.

2. The problem of not introducing generics - no type exception checking during compilation

1 Code

import .*;
public class ListErr
{
  public static void main(String[] args)
  {
   // Create a List collection that only wants to save strings   List strList = new ArrayList();
   ("Crazy Java Handout");
   ("Crazy Android Handout");
   // "accidentally" throw an Integer object into the collection   (5);   // Section A   (str -> (((String)str).length())); // Position B  }
}

2 Run

Exception in thread "main" : cannot be cast to
8
    at $main$0(:14)
11
    at (:1257)
    at (:14)

3 Description

The program accidentally "drops" an Integer object into the List collection at A, which will cause the program to raise a ClassCastException at B because the program tries to convert an Integer object to a String type.

3. Introducing generic combat

1 Code

import .*;
public class GenericList
{
  public static void main(String[] args)
  {
   // Create a List collection that only wants to save strings   List<String> strList = new ArrayList<String>(); // ①
   ("Crazy Java Handout");
   ("Crazy Android Handout");
   // The following code will cause a compilation error   //(5);  // ②
   (str -> (())); // ③
  }
}

2 Run

8
11

3 Description

Use generics in collections brings the following advantages:

  • The program can no longer "accidentally" throw other objects into the strList collection, and the compiler will prompt for a compiler alarm;
  • The program is more concise, and the collection automatically remembers the data types of all collection elements, so that there is no need to cast the collection elements.

Four Java 7 generic diamond syntax practice

1 Code

import .*;
public class DiamondTest
{
  public static void main(String[] args)
  {
   // Java automatically infers that the <> of ArrayList should be String   List&lt;String&gt; books = new ArrayList&lt;&gt;();
   ("Crazy Java Handout");
   ("Crazy Android Handout");
   // traverse books collection, the collection element is the String type   (ele -&gt; (()));
   // Java automatically infers that the <> of HashMap should be String and List<String>   Map&lt;String , List&lt;String&gt;&gt; schoolsInfo = new HashMap&lt;&gt;();
   // Java automatically infers that the <> of ArrayList should be String   List&lt;String&gt; schools = new ArrayList&lt;&gt;();
   ("Silent Moon Three Star Cave");
   ("The Way to Get the Path in the West");
   ("Sun Wukong" , schools);
   // When traversing the Map, the key of the Map is String type and the value is List<String> type   ((key , value) -&gt; (key + "--&gt;" + value));
  }
}

2 Run

8
11
Sun Wukong-->[Sanxing Cave of the Shallow Moon, the Way to the West to Get the Pastoral]

3 Description

The diamond syntax has not changed the original generics, but has better simplified generic programming.

For more Java-related content, please view the topic of this site:Introduction and Advanced Tutorial on Object-Oriented Programming in Java》、《Java Data Structure and Algorithm Tutorial》、《Summary of Java's DOM node skills》、《Summary of Java files and directory operation skills"and"Summary of Java cache operation skills

I hope this article will be helpful to everyone's Java programming.