You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
Luojiale 3557013fe8 Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
..
Box.class Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
Box.java Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
GenericDemo.class Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
GenericDemo.java Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
GenericUtils.class Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
GenericUtils.java Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
Pair.class Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
Pair.java Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago
README.md Add w5 to w11 projects: shape inheritance, animal interface, exception handling, generics, maven project, repository with analyze command, exception hierarchy with retry 3 weeks ago

README.md

Java 泛型类练习

本项目包含几个典型的 Java 泛型类练习,展示了泛型的使用方法。

文件结构

  1. Box.java - 简单的泛型容器类
  2. Pair.java - 存储键值对的泛型类
  3. GenericUtils.java - 包含泛型方法的工具类
  4. GenericDemo.java - 演示程序
  5. README.md - 本文档

泛型类概述

Box

一个简单的泛型容器类,可以存储任意类型的对象。

  • 使用单个类型参数 T
  • 提供构造函数、getter、setter 方法
  • 判断是否为空的方法

Pair<K, V>

一个存储键值对的泛型类,可以存储两个不同类型的对象。

  • 使用两个类型参数 K 和 V
  • 提供构造函数和 getter/setter 方法

GenericUtils

一个包含泛型方法的工具类,展示了如何创建和使用泛型方法。

  • printArray: 打印任意类型数组的元素
  • swap: 交换数组中的任意两个元素
  • countListElements: 计算列表中的元素数量

编译运行

# 编译所有 Java 文件
javac Box.java Pair.java GenericUtils.java GenericDemo.java

# 运行演示程序
java GenericDemo

运行结果

程序会展示泛型类的各种用法,包括:

  • Box 类存储不同类型的数据
  • Pair 类存储键值对
  • GenericUtils 的泛型方法的使用

泛型的主要优点

  1. 类型安全:编译时检查,避免运行时类型错误
  2. 代码复用:一套代码支持多种数据类型
  3. 可读性:更清晰的代码,更易理解
  4. 避免强制类型转换:减少代码中的类型转换