I have an generic array(it keeps set of element and element of type is generic(maybe int,maybe char, maybe String etc.)
And also I think a set is sorted so I wanted to use bubblesort algorithm.But
I took // bad operand types for binary operator '>' this error message.
What can I do for this sort function work some different data type(String,int,char,double)
This is my code :
void bubbleSort(T arr[]){
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j] > arr[j+1]){ // bad operand types for binary operator '>'
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
Edit1:
If I tried compareTo:
void bubbleSort(T arr[]){
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j].compareTo(arr[j+1])<0){ // bad operand types for binary operator '>'
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
The error message is :
cannot find symbol
symbol: method compareTo(T)
location: class Object
where T is a type-variable:
T extends Object declared in class MySet
Edit2 : If I tried this:
<T extends Comparable<T>> void bubbleSort(T arr[]) {
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j].compareTo(arr[j+1])> 0) {
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
When calling the function bubbleSort:
private T[] data;
bubbleSort(data);
The error message is :
method bubbleSort in class Set<T#2> cannot be applied to given types;
required: T#1[]
found: T#2[]
reason: inference variable T#1 has incompatible bounds
upper bounds: Comparable<T#1>
lower bounds: T#2
where T#1,T#2 are type-variables:
T#1 extends Comparable<T#1> declared in method <T#1>bubbleSort(T#1[])
T#2 extends Object declared in class Set
----
(Alt-Enter shows hints)
Edit3:
If I try this:
void bubbleSort(Comparable arr[]) {
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j].compareTo(arr[j+1])> 0) {
Comparable temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
And call the function bubbleSort :
private T[] data;
bubbleSort(data);
The error message is:
incompatible types: T[] cannot be converted to Comparable[]
where T is a type-variable:
T extends Object declared in class MySet
----
(Alt-Enter shows hints)
compareTo()insteadTimplement Comparable<T> and usecompareTo.