简体   繁体   English

Java泛型和扩展

[英]java generics and extends

I've read the docs but don't see what I'm doing wrong here ... the goal is a generic collection class Wlist to contain ItemIFs. 我已经阅读了文档,但在这里看不到我做错了什么……目标是包含ItemIF的通用集合类Wlist。 The Java source for java.util.TreeMap uses: java.util.TreeMap的Java源使用:

public V put(K key, V value) {
  Comparable<? super K> k = (Comparable<? super K>) key;
  cmp = k.compareTo(t.key);

I was hoping to avoid the cast by using the code below, but get a warning "unchecked call" when I compile with -Xlint:unchecked. 我希望通过使用下面的代码来避免强制转换,但是当我使用-Xlint:unchecked进行编译时,会收到警告“ unchecked call”。 Suggestions? 建议?

interface ItemIF<TP> {
  int compareItem( TP vv);
} // end interface ItemIF


class Wlist<TP extends ItemIF> {
TP coreItem;
void insert( TP item) {
  // *** Following line gets: warning: [unchecked] unchecked call   ***
  // *** to compareItem(TP) as a member of the raw type ItemIF      ***
  int icomp = coreItem.compareItem( item);
}
} // end class


class Item implements ItemIF<Item> {
String stg;
public Item( String stg) {
  this.stg = stg;
}
public int compareItem( Item vv) {
  return stg.compareTo( vv.stg);
}
} // end class Item


class Testit {
public static void main( String[] args) {
  Wlist<Item> bt = new Wlist<Item>();
  bt.insert( new Item("alpha"));
}
} // end class Testit

Try 尝试

class Wlist<TP extends ItemIF<TP>>

otherwise you are using ItemIF as a raw type giving you the raw type warning. 否则,您将ItemIF用作原始类型,并向您发出原始类型警告。

public int compareItem( Item vv)

Uses Item not ItemIF so you are downcasting when you call it with TP extends ItemIF . 使用Item而不是ItemIF因此当您使用TP extends ItemIF调用时,您将向下转换。

Try changing it to 尝试将其更改为

public int compareItem( ItemIF vv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM