[英]pass integer array to comparable in java
public class Stack {
public static void main(String[] args) {
// Strings[]
// names={"news","ask","man","querty","lang","love","poppye","zebra","hello"};
int[] names = { 31, 5343, 8776, 90, 123, 33 };// shows me an error
Selection sec = new Selection();
sec.sort(names);
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
}
class Selection {
int valNow;
public void sort(Comparable[] names) {
for (int i = 0; i < names.length; i++) {
boolean swapOn = false;
int min = -200;
int pointer = 0;
for (int j = i + 1; j < names.length; j++) {
if (less(names[i], names[j])) {
if (valNow > min) {
min = valNow;
pointer = j;
System.out.println("Pointer:" + pointer + " "
+ "Highest:" + min);
swapOn = true;
}
}
}
if (swapOn) {
swap(names, i, pointer);
}
}
}
public void swap(Comparable[] name, int x, int y) {
System.out.println("Gonna swap:" + name[x] + " and " + name[y]);
Comparable inter = name[x];
name[x] = name[y];
name[y] = inter;
}
public boolean less(Comparable one, Comparable two) {
boolean send = false;
valNow = one.compareTo(two);
System.out.println(valNow);
if (valNow > 0) {
send = true;
} else if (valNow == 0) {
send = true;
}
return send;
}
}
I am able to pass and sort String array to Comparable[] in selection class sort() method but passing int array to sort() shows me error that Comparable[] is not applicable to int[]!!I need to sort all types of data with same code! 我可以在选择类sort()方法中将String数组传递并排序到Comparable [],但是将int数组传递给sort()则显示错误,Comparable []不适用于int []!我需要对所有类型进行排序具有相同代码的数据! Please help me out! 请帮帮我!
Use Integer
instead of int
. 使用Integer
而不是int
。 int
is not a class and have no compareTo method. int
不是一个类,并且没有compareTo方法。
您应该使用Integer而不是int。
In Java, arrays are covariant, which means if class C
implements interface I
then C[]
can be treat as I[]
. 在Java中,数组是协变的,这意味着如果类C
实现接口I
则C[]
可以视为I[]
。 On other hand, String
class implements Comparable
interface, so an array of String
s can be considered as an array of Comparable
s, but int[]
is an array of primitive int
, and int
doesn't implement any interface. 另一方面, String
类实现Comparable
接口,因此可以将String
的数组视为Comparable
的数组,但是int[]
是原始int
的数组,而int
不实现任何接口。 You should use instead Integer[]
. 您应该改为使用Integer[]
。
int
is a primitive type, while Comparable
is a reference type. int
是原始类型,而Comparable
是引用类型。 Use the reference type Integer
instead, which is a subtype of Comparable
. 请改用引用类型Integer
,它是Comparable
的子类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.