[英]Applying insertion sort to arrays of objects
I'm trying to apply insertion sort to an array of objects but my else if never compiles and says "bad operand types". 我试图将插入排序应用于对象数组,但是如果没有编译并说“错误的操作数类型”,则不然。
Just wondering if I need to make a very specific compareTo
method or if there's a better way of comparing arrays of objects in an insertion sort method. 只是想知道我是否需要做一个非常具体的
compareTo
方法,或者是否有更好的方法比较插入排序方法中的对象数组。
EDIT: 编辑:
So here's me trying to use my compareTo
method and it compiles but I get a null pointer exception
on the else if
. 所以这是我尝试使用
compareTo
方法进行编译的方法,但是在else if
上得到了null pointer exception
。 Why? 为什么?
public static void insertElement(WordClass[] Words, int next)
{
WordClass value = Words[next];
int i = next;
while(true)
{
//
if(i == 0)
{
Words[0] = value;
break;
}
else if(Words[i-1].getStr().compareTo(value.getStr()) <= 0)
{
Words[i] = value;
break;
}
else
{
Words[i] = Words[i-1];
i--;
}
}
}
public static void insertionSort(WordClass[] Words)
{
for(int i = 1; i< Words.length; i++)
{
insertElement(Words, i);
}
}
//in WordClass
public int compareTo(WordClass w) //makes WordClass comparable
{
return getStr().compareTo(w.getStr());
}
You should always use campareTo
instead of ==
or <=
operators for object types, unless you want to campare two object variables to see if both refers to same object. 对于对象类型,应始终使用
campareTo
而不是==
或<=
运算符,除非您希望对两个对象变量进行比较,以查看它们是否都引用同一对象。 Also your WordClass
class must implement the Camparable
interface in order for this to work. 同样,您的
WordClass
类必须实现Camparable
接口,以使其正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.