Java中的泛型是什么? [英] What are Generics in Java?

查看:17
本文介绍了Java中的泛型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白泛型的意义.它们是做什么的,你如何使用它们?

I don't really understand the point of generics. What do they do, how do you use them?

据我所知,他们所做的只是在编译时而不是运行时检查返回类型,以避免在抛出错误之前运行程序.这就是他们所做的一切吗?

From what I can tell, all they do is check return types at compile times instead of run times to avoid running the program before an error is thrown. Is this all they do?

例如:

public <Integer> int test() {
    return 'c'; //will throw error at compile instead of runtime
}

我在读一些关于泛型是如何任意的,你应该只使用大写字母吗?这有点令人困惑.

I was reading something about how generics are arbitrary, and you should only use capital letters? This is kind of confusing.

推荐答案

泛型允许您自定义泛型"方法或类到您正在使用的任何类型.例如,假设您有一个将两个数字相加的方法.为了使用类型本身,您可能必须创建此方法的多个版本.例如:

Generics allow you to customize a "generic" method or class to whatever type you're working with. For example, suppose you have a method that adds two numbers together. In order to work with the types themselves, you might have to create multiple versions of this method. For instance:

public int Add(int a, int b)

public double Add(double a, double b)

public float Add(float a, float b)

泛型允许您创建一个为调用它的类型定制的方法.

Generics allow you to create a single method that is customized for the type that invokes it.

public <T> T Add(T a, T b)

T 替换为您使用的任何类型.

T is substituted for whatever type you use.

这篇关于Java中的泛型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆