简体   繁体   中英

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. The Java source for java.util.TreeMap uses:

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. 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.

public int compareItem( Item vv)

Uses Item not ItemIF so you are downcasting when you call it with TP extends ItemIF .

Try changing it to

public int compareItem( ItemIF vv)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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