This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have the following bit of code where I am trying to use the Collections.binarySearch() method:
KeySet is a custom class with an iterator() method with the following signature:
When I compile this code, I get the following error message:
I don't know enough about generics to understand why this won't compile. Everything seems fine to me! Apparently I am missing some nuance to the generic mechanism that is biting me in the bud here. I would greatly appreaciate anyone that can help me figure out how to fix this.
Does your ByteArrayComparator implement Comparator<byte> or Comparator<? super byte>? I don't see that in the post.
Joined: Dec 06, 2001
Originally posted by Satou kurinosuke: I don't know anything about Generics either but I looked at Collections API: public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
I wonder if you can actually use primitives (like bytes, or array of bytes) with this method. It doesn't seem so. Instead, did you try it on objects like String ?
You are correct that you have to be careful with primitives like byte, int, float, etc. However, arrays are NOT primitives. They are objects and can be treated as such. Unless there is some special case in an instance like this.
Joined: Dec 06, 2001
Originally posted by Paul Clapham: Does your ByteArrayComparator implement Comparator<byte> or Comparator<? super byte>? I don't see that in the post.
I didn't think I would need to post my comparator class. It is
This could possibly be the problem. In fact, I'm not quite sure what Comparator<? super byte>? means exactly. Can someone explain? Or at least point me to a good online tutorial? I guess I should just check out Sun's official tutorials to see what they have to say about this.
No, if I understand it (not a foregone conclusion) then that should be good enough. But don't ask me to explain <? super T>, I don't understand it that well. The tutorial does explain it (google for "java generics tutorial"). It also goes into a couple of examples that explain why arrays don't fit well with generics. That might be your problem but the examples looked a lot different than what you are trying. They were mostly trying to show why you can't have an array of a generic type.
The compiler doesn't complain when you use an array type as your class parameter, so it's possible that you are seeing a compiler bug. Not very likely, though, or somebody would surely have encountered it by now. But you could check the bug database, I wouldn't rule it out.