在Java HashMap中,如何强制泛型成为子类 [英] In Java HashMap, how to enforce a generic type to be a subclass
本文介绍了在Java HashMap中,如何强制泛型成为子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是一个跟踪东西及其所有者的类。
public class Record< S,O> {// S - 通用的东西,O - 通用的所有者
HashSet< S> allStuffs;
HashMap< S,O> whoOwnsWhat;
//
}
如何执行S必须是子类某些类/接口。
谢谢。
编辑:
我修改记录为 class Record< Stuff,O>
其中Stuff是一个抽象类,并且收到警告类型参数Stuff隐藏类型Stuff。
public class< S extends Stuff>记录< S,O>
也会收到编辑投诉。
解决方案
定义Java泛型的界限。
public class Record& S extends fooClassName,O> {
HashSet allStuffs(fooClassName arg); //通过将S HashSet< S>< S> allStuffs;
HashMap whoOwnsWhat(fooClassName arg1,O arg2);
}
I'm a class that keeps track of stuffs and their owners
public class Record<S,O> { //S - generic stuff, O - generic owner
HashSet<S> allStuffs;
HashMap<S, O> whoOwnsWhat;
//
}
How can I enforce that S must be subclass of certain class/interface.
Thank you.
EDIT:
I modified Record to be "class Record<Stuff,O>"
where Stuff is an abstract class, and got a warning "the type parameter Stuff is hiding the type Stuff".
public class <S extends Stuff> Records<S,O>
also get a complier complaint.
解决方案
There are extends and super keywords to define bounds for Java generics.
public class Record<S extends fooClassName,O> {
HashSet allStuffs(fooClassName arg); // do not "override" S by putting S HashSet<S> allStuffs;
HashMap whoOwnsWhat (fooClassName arg1, O arg2);
}
这篇关于在Java HashMap中,如何强制泛型成为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文