Java泛型:多个泛型参数? [英] Java generics: multiple generic parameters?

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

问题描述

  public int void myfunction(设置< T> a,设置< T> b){
return 5;
}

Set< Integer> setA = new HashSet< Integer>();
Set< String> setB = new HashSet< String>();
int result = myfunction(setA,setB);

这会起作用吗?每个参数中的泛型是否意味着每个参数必须具有通用的相同类型T?

谢谢!

是 - 有可能(尽管不是您的方法签名),是的,签名的类型必须相同。

有了您签署的签名, T 必须与单一类型关联(例如字符串 整数)。但是,您可以声明具有多个类型参数的方法签名。

  public< S,T> void func(Set< S> s,Set< t>)

我已经在签名中声明了类型 S T 。因此这些不同于并且独立于与包含该功能的类或接口相关联的任何通用类型。

  public class MyClass< S,T> {
public void foo(Set< S> s,Set< T> t); //与class
中相同的参数params public< U,V>空栏(Set s,Set t); //类型params独立于类
}

您可能会喜欢看一些集合类的方法签名在 java.util 包中。泛型实际上是一个相当复杂的主题,尤其是当考虑通配符(?extends ?super )时。例如,一个可能采用 Set > 作为参数的方法通常也应该接受 Set< Integer> 。在这种情况下,你会看到这样的签名:

  public void baz(Set< ;? extends T> s); 

现在已经有很多问题可供您参考!





不知道从函数中返回 int 的意义是什么,尽管如果你想要的话可​​以这样做!


I was wondering if it's possible to write a function that accepts multiple generic types as follows:

public int void myfunction(Set<T> a, Set<T> b) {
    return 5;
}

Set<Integer> setA = new HashSet<Integer>();
Set<String> setB = new HashSet<String>();
int result = myfunction(setA, setB);

Will that work? Does the generic in each parameter mean that each parameter must have the same type T that's generic?

Thanks!

解决方案

Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.

With the signature you have given, T must be associated to a single type (e.g. String or Integer) at the call-site. You can, however, declare method signatures which take multiple type parameters

public <S, T> void func(Set<S> s, Set<T> t)

Note in the above signature that I have declared the types S and T in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.

public class MyClass<S, T> {
   public        void foo(Set<S> s, Set<T> t); //same type params as on class
   public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}

You might like to take a look at some of the method signatures of the collection classes in the java.util package. Generics is really rather a complicated subject, especially when wildcards (? extends and ? super) are considered. For example, it's often the case that a method which might take a Set<Number> as a parameter should also accept a Set<Integer>. In which case you'd see a signature like this:

public void baz(Set<? extends T> s);

There are plenty of questions already on SO for you to look at on the subject!

Not sure what the point of returning an int from the function is, although you could do that if you want!

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

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