知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

      • Theory:Functional decomposition
      • Theory:Paradigms
      • Theory:Overloading
      • Theory:Write, compile, and run
      • Theory:Annotations basics
      • Theory:JVM, JRE, and JDK
      • Theory:Jave Archive
      • Theory:Running programs on your computer
      • Theory:Enums in Java
      • Theory:Fields and methods in enum
      • Theory:StringBuilder
      • Theory:Immutability
      • Theory:Boxing and unboxing
      • Theory:Introduction to generic programming
      • Theory:Generics and Object
      • Theory:What are collections
      • Theory:The collections Framework overview
      • Theory:ArrayList
      • Theory:The List interface
      • Theory:Comparable
      • Theory:Processing strings
      • Theory:Initialization blocks
      • Theory:Introduction to API
      • Theory:Generic methods
        • Generic static methods
        • Generic instance methods
        • Conclusion
    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 应知
Jim
2022-11-24
目录

Theory:Generic methods

In previous topics we have discussed generic classes and how one can use them. But Java also has generic methods that can be very useful. Generic methods allow type parameters to be passed to a method and used in its logic. They also allow a type parameter to be the return type.

All methods can declare their own type parameters, regardless of the class they belong to. This means that a non-generic class can contain generic methods.

提示

Static methods cannot use type parameters of their class! Type parameters of the class these methods belong to can only be used in instance methods. If you want to use type parameters in a static method, declare this method's own type parameters.

Let's take a look at examples of generic static and instance methods and find out how they are used.

# Generic static methods

The following static method is declared as generic. The declaration of the generic type T surrounded by angle brackets allows us to use this type in the method. We remind you that it can belong to a generic or a non-generic class because it does not matter for generic methods.

public static <T> T doSomething(T t) {
    return t;
}
1
2
3

The type parameter T can be used to declare the return type and the type of the method's arguments. A generic method can take or return values of non-generic types as well. For instance, the following method takes a generic array and returns its size as an int.

public static <E> int length(E[] array) {
    return array.length;
}
1
2
3

A generic method's body is declared like that of any other method.

We can pass an array of integers to the method we defined earlier and find its length:

Integer[] array = { 1, 2, 3, 4 };
int len = length(array); // pass an array of Integers
1
2

We could use this same method to find the length of an array of Strings (or any other reference type).

String[] stringArray = { "a", "b", "c", "d" };
len = length(stringArray); 
1
2

提示

Recall that type parameters can represent only reference types, not primitive types.

As another example of a generic method, take a look at one that prints the elements of a generic array.

public static <E> void print(E[] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
    System.out.println();
}
1
2
3
4
5
6

Let's create an array and print it using this method.

Character[] characters = { 'a', 'b', 'c' };
print(characters);
1
2

The output will be:

a b c 
1

提示

In this example, we used the void keyword in the declaration of the method because the method does not return anything.

Just like in generic classes, the type parameter section can contain multiple type parameters separated by commas.

For instance, the following method declares two type parameters.

public static <T, U> void method(T t, U u) {
    // do something
}
1
2
3

Static generic methods are often used to write generic algorithms that do not depend on the type they operate on. This can be convenient when the method has to be used independently from the class it belongs to. We frequently use generic static methods for different operations with arrays and collections: sorting an array, searching for a value in a collection, reversing an array, and so on.

# Generic instance methods

Just like static methods, instance methods can have their own type parameters. There is no difference in their declaration compared to static methods, excluding the absence of the static keyword.

class SimpleClass {
 
    public <T> T getParameterizedObject(T t) {
        return t;
    }
}
1
2
3
4
5
6

The class above does not provide a type parameter, so we have to specify the type parameter in the method declaration to make the method getParameterizedObject generic.

提示

Note that in this example we cannot use T as the type for a field in the class, because it belongs to the method rather than the class itself.

Now we can create an instance of the class and invoke the method. It will return a value that has the same type as the value that was passed in.

SimpleClass instance = new SimpleClass();
Integer value = instance.getParameterizedObject(601); // this will return 601
1
2

Although generic methods can belong to non-generic classes, it is more common for a generic method to belong to a class that is also generic. Below is an example of a generic class that contains a generic instance method.

class SimpleClass<T> {
 
    public <U> T getParameterizedObject(T t, U u) {
        return t;
    }
}
1
2
3
4
5
6

The method receives arguments of both the class's type (T) and the method's own type (U). Because T was already declared in the class header, the method only has to declare the generic type U. The method returns the variable of type T.

# Conclusion

Generic methods are a must-have for programmers since they allow us to restrict the scope of type parameters to a single function. Type parameters in generic methods can be used as return types or as types for arguments passed to the function. Both static and instance methods can be generic.

编辑 (opens new window)
#Generic#Java
上次更新: 2022/12/03, 17:31:39
Theory:Introduction to API
Theory:Units of information

← Theory:Introduction to API Theory:Units of information→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式