java接口问题,本人菜鸟,求教大神
简单的程序:
1.这是一个接口:
interface Comparable<T> {
public int comparaTo(T y);
}
2.这是一个类以及其中的方法:
public class Sort implements Comparable{
public static void insertionSort(int[] a){
int i,j,n=a.length;
int key;
for(j=1;j<n;j++){
key=a[j];
i=j-1;
while(i>=0&&a[i]>key){
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
public static void insertionSort(Comparable[] a){
int i,j,n=a.length;
Comparable key;
for(j=1;j<n;j++){
key=a[j];
i=j-1;
while(i>=0&&a[i].comparaTo(key)>0){
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
@Override
public int comparaTo(Object y) {
// TODO Auto-generated method stub
return 0;
}
}
3.这是一个主类:
public class Test1 {
/**
* @param args
*/
public static void main(String args[]) {
// TODO Auto-generated method stub
Integer[] a={5,1,0,3,4,6,7,2,9,8};
String[] b={"xingtai","chongqing","beijing","shijiazhuang","tangshan"};
Double[] c={1.8,2.3,4.2,2.5,4.4,7.4};
int i1=a.length,i2=b.length,i3=c.length;
Sort.insertionSort(a);
for(int i=0;i<i1;i++){
System.out.println(""+a[i]);
}
Sort.insertionSort(b);
for(int i=0;i<i2;i++){
System.out.println(""+b[i]);
}
}
}
问题描述:上述主类中的Sort.insertionSort(a);与Sort.insertionSort(b);都有错误,难道不能用Comparable[]代替Integer[]和String[]吗,这似乎与C++里的模板差不多吧,大神们,小弟在这求教了
------解决方案--------------------Comparable是java里已经存在的接口了。
------解决方案--------------------LZ把你自定义的Compareable接口去掉,把Sort类换成我这样的试试
// 无需实现Compareable接口
public class Sort{
public static void insertionSort(int[] a) {
int i, j, n = a.length;
int key;
for (j = 1; j < n; j++) {
key = a[j];
i = j - 1;
while (i >= 0 && a[i] > key) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}
public static void insertionSort(Comparable[] a) {
int i, j, n = a.length;
Comparable key;
for (j = 1; j < n; j++) {
key = a[j];
i = j - 1;
while (i >= 0 && a[i].compareTo(key) > 0) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
}
}
}