java中什么叫做泛型,什么是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?

for example:

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

T is substituted for whatever type you use.

你可能感兴趣的:(java中什么叫做泛型)