0

我有一个包含一些字符串以及一些整数值的类。该程序需要使用冒泡排序来按名为 studentID 的特定整数进行排序。

我遇到的问题是正确访问变量。我们需要将类中的变量保持为私有,因此原始值不能从实际类内部以外的任何地方直接访问。

我有这样的设置

public class Student {
    // PRIVATE strings and ints

    public Student() {
        // set variables to text fields
    }

    public void bubbleSort() {
        int i, j, temp;

        for (i = (x-1); i >= 0; i--) {    
            for (j = 1; j <= i; j++) {    
                if(x[j - 1] > students[j]) {
                    temp = x[j - 1];
                    x[j - 1] = x[j];
                    x[j] = temp; 
                }
            } 
        }
    } 
}

对于每次出现的 X,我都需要 myStudent.studentID 的值。冒泡排序是要在类中实现的,但我不知道如何调用它。将所需字段设置为私有,我无法找到要排序的信息。

4

2 回答 2

3

在Student类中实现IComparable接口,然后使用CompareTo()代替bubbleBort中的“<”操作符。这将解决私有变量的问题。

在这些更改之后,BubbleSort 可以重写为静态泛型方法。

public static void bubbleSort<T>(T[] array) where T : IComparable{
    int i, j;
    T temp;

    for (i = (x-1); i >= 0; i--) 
{    
    for (j = 1; j <= i; j++) 
{    
    if(array[j - 1].CompareTo(array[j]) == 1) 
{
    temp = array[j - 1];
    array[j - 1] = array[j];
    array[j] = temp; 
} } } }
于 2011-01-23T15:15:25.240 回答
1

您使用属性将私有字段暴露给外部。

private string text = "";

public string Text
{
  get { return text; }
  set { text = value; }
}

如果不允许您这样做,您应该与您的老师交谈,因为那时无法与班级互动。

于 2011-01-23T15:05:53.693 回答