Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections.sort and generics

 
Maxim Katcharov
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I'm missing something with generics. Here's the code that I'm having trouble with:


class Foo implements Comparable {...

... within another class:

private List<Foo> fooList;

void addFoo(Foo f) {
fooList.add(f);
Collections.sort(fooList); //gives me an error
}


the error:
the generic method sort(List<T> of type Collections is not applicable for the arguments (List<Foo> since the type Foo is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>


could someone explain what's going on?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look carefully at the message - "the type Foo is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>"
It's not enough that Foo implements Comparable; you need to implement Comparable<Object> or Comparable<Foo>.
 
Maxim Katcharov
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and it all makes sense. Thanks Jim.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic