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

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

问题描述

我真的不明白泛型点。他们做什么,你如何使用它们?



从我可以告诉的,他们所做的只是在编译时检查返回类型,而不是运行时间,以避免运行程序抛出错误之前。这是他们所做的一切吗?



例如:

  public< ;整数> int test(){
return'c'; //将在编译时抛出错误而不是运行时
}

我正在阅读有关如何泛型是任意的,你应该只用大写字母吗?这是一种混乱。

解决方案

泛型允许您自定义通用方法或类与你正在使用的任何类型例如,假设您有一个方法可以将两个数字加在一起。为了使用类型本身,您可能需要创建此方法的多个版本。例如:

  public int Add(int a,int b)

public double Add a,double b)

public float Add(float a,float b)

泛型允许您创建一个为调用它的类型自定义的方法。

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

T 代替您使用的任何类型。


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?

for example:

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 Add<T>(T a, T b)

T is substituted for whatever type you use.

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

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