那是我的通用冒泡排序器的 Java 代码:
public class BubbleSorter<E extends Comparable<E>> {
E[] a;
void swap(int i, int j) {
E temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void bubbleSort(E[] a) {
this.a=a;
for (int i=0 ;i<a.length;i++) {
for (int j=0;j<a.length;j++) {
if ( a[i].compareTo(a[j]) > 0) swap(i,j);
}
}
}
}
public interface Comparable<E> {
public int compareTo(E e);
}
这是一个使用示例:
public class Test {
public static void main (String arg[]) {
Rational[] a = new Rational[3];
a[0]=Rational.rationalFactory(9,2);
a[1]=Rational.rationalFactory(1,3);
a[2]=Rational.rationalFactory(10,11);
Complex[] b = new Complex[3];
b[0]=new Complex(7,5);
b[1]=new Complex(3,4);
b[2]=new Complex(8,9);
BubbleSorter<Rational> br=new BubbleSorter<Rational>();
BubbleSorter<Complex> bi=new BubbleSorter<Complex>();
br.bubbleSort(a);
bi.bubbleSort(b);
for (int i=0 ; i < 3 ; i++ ) {
System.out.print(a[i] + " ");
}
System.out.println();
for (int i=0 ; i < 3 ; i++ ) {
System.out.print(b[i] + " ");
}
}
}
public class Rational implements Comparable<Rational> {
int mone,mehane;
private Rational(int n,int m) {
mone=n;
mehane=m;
}
static public Rational rationalFactory(int n,int m) {
if (n==0) return null;
return new Rational(n,m);
}
public String toString() {
return mone + "/" + mehane;
}
public int compareTo(Rational r) {
return (r.mehane*mone - r.mone*mehane);
}
}
public class Complex implements Comparable<Complex> {
int real,img;
public Complex(int r,int i) {
real=r;
img=i;
}
public String toString() {
return real + "+" + img + "i";
}
public int compareTo(Complex r) {
double x=(getLength() - r.getLength());
if (x>0) return 1;
if (x==0) return 0;
return -1;
}
public double getLength() {
return Math.sqrt(real*real+img*img);
}
}
当我尝试将我的 Java 代码转换为 C# 时,我被困在试图强制泛型类型扩展 Comparable 因为< E : Comparable >不起作用。我该如何克服呢?
这就是我尝试过的:
abstract class Comparable<E> {
static bool operator ==( Comparable<E> e1, Comparable<E> e2 );
static bool operator !=( Comparable<E> e1, Comparable<E> e2 ) {
return !( e1 == e2 );
}
static bool operator >( Comparable<E> e1, Comparable<E> e2 );
static bool operator >=( Comparable<E> e1, Comparable<E> e2 ) {
if ( e1 > e2 ) return true;
if ( e1 == e2 ) return true;
return false;
}
static bool operator <=( Comparable<E> e1, Comparable<E> e2 ) {
return !( e1 > e2 );
}
static bool operator <( Comparable<E> e1, Comparable<E> e2 ) {
return !( e1 >= e2 );
}
}
public class BubbleSorter<E : Comparable<E>> {
E[] a;
void swap(int i, int j) {
E temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void bubbleSort(E[] a) {
this.a=a;
for (int i=0 ;i<a.length;i++) {
for (int j=0;j<a.length;j++) {
if ( a[i]>a[j] ) swap(i,j);
}
}
}
}