Hi, I am currently learning all the common sort algorithms, and the course is in Java. Now my difficulty is not about any sort algorithm in particular (well, as of yet), but how to write a generic implementation instead of hard-coding integers or doubles.
Consider this code :
public static <AnyType extends Comparable<? super AnyType>>
void insertionSort( AnyType[] a ) {
...
}
I have two questions about this code :
- Is it normal that in order to instantiate an array of AnyType, I have to write AnyType[] a = (AnyType[])new Comparable ? This generates a warning.
- What does the bit between <> mean at the top of the method ? AnyType has to implement Comparable<T> where T derives from AnyType ? :wacko:
Now in C#, you can create generic arrays alright, but consider the following code:
public bool IsSorted<T>(T[] Elements) {
...
}
Obviously, in order to test if Elements is sorted, I need to call CompareTo(T) on each Element[x]. That supposes T implements IComparable. Or is it IComparable<T> ? Or something as complicated as the Java syntax ? In any case, how do I tell the compiler that T implements the right interface ?
Question
Andre S. Veteran
Hi, I am currently learning all the common sort algorithms, and the course is in Java. Now my difficulty is not about any sort algorithm in particular (well, as of yet), but how to write a generic implementation instead of hard-coding integers or doubles.
Consider this code :
public static <AnyType extends Comparable<? super AnyType>> void insertionSort( AnyType[] a ) { ... }I have two questions about this code :
- Is it normal that in order to instantiate an array of AnyType, I have to write AnyType[] a = (AnyType[])new Comparable ? This generates a warning.
- What does the bit between <> mean at the top of the method ? AnyType has to implement Comparable<T> where T derives from AnyType ? :wacko:
Now in C#, you can create generic arrays alright, but consider the following code:
public bool IsSorted<T>(T[] Elements) { ... }Obviously, in order to test if Elements is sorted, I need to call CompareTo(T) on each Element[x]. That supposes T implements IComparable. Or is it IComparable<T> ? Or something as complicated as the Java syntax ? In any case, how do I tell the compiler that T implements the right interface ?
Thanks.
Edited by Dr_AsikLink to comment
Share on other sites
9 answers to this question
Recommended Posts