Java中的泛型是什么?

编程入门 行业动态 更新时间:2024-10-26 10:32:06
本文介绍了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中的泛型是什么?

本文发布于:2023-11-09 10:31:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!