如何使用比较器执行此代码?
抱歉,我已经很久没有使用Java了。我有一个对 int 类型进行排序的类,我正在尝试执行此操作,但这无法编译:
MySort.sort(vectorOfInt, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (int)o1 - (int)o2;
}
});
我想使用此方法使用比较器按升序排序对 int 向量进行排序。
public static void sort(T[] a, Comparator c) {
sort(a, 0, a.length, c);
}
Sorry, I don't work with Java since a long time. I have a class which sort int type, and I am trying to do this, but this does not compile:
MySort.sort(vectorOfInt, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (int)o1 - (int)o2;
}
});
I would like to sort a vector of int using this method using the comparator to sort in ascending order.
public static void sort(T[] a, Comparator c) {
sort(a, 0, a.length, c);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
示例代码相当不完整,但首先您不能将 Object 强制转换为 int。 代替使用
。
The sample code is rather incomplete, but to begin with you cannot cast Object to int. Use
instead.
首先,不要使用
Vector
或Hashtable
,出于所有实际目的,它们都被视为已弃用
。使用List
或Map
实现。请改用
List
,这是将Integer
列表作为对象进行操作的现代且正确的方法。如果您想使用不同的
Comparator
,那么您可以使用:由于
Integer
实现了Comparable
,因此默认情况下会对List
进行排序。 Integer>
按升序排列。 Integer 了解详细信息。这是现代 Java 中对
List
和Collection
类进行排序的正确且惯用的方法。任何其他情况都表明您不理解该语言及其提供的内容。First off, don't use
Vector
, orHashtable
for that matter, they both are considereddeprecated
for all practical purposes. UseList
orMap
implementations.Use a
List<Integer>
instead, it is the modern and correct way to manipulate a list ofInteger
s as objects.If you want to use a different
Comparator
then you can use:Since
Integer
implementsComparable
, this will by default sort theList<Integer>
in ascending order. Integer for the details.This is the correct, idiomatic way of sorting
List
andCollection
classes in modern Java. Anything else shows you don't understand the language and what it provides.你可以制作一个类型化比较器并且你赢了不需要抛出参数。
编辑:
首先,请不要将数组称为向量。
向量
是一个 java 类,当您命名变量vectorOfInt
时,人们会假设您正在使用它。您收到的编译器错误是因为编译器不知道您的
Comparator
正在对Integer
进行操作。由于它看到的只是一个Object
,因此它不知道 o1 实际上是一个Integer
并且可以拆箱为int
。通过指定比较器类型,您可以提供更多信息并且可以隐式进行转换。You can make a typed Comparator and you won't need to cast the arguments.
EDIT:
First off, please don't call an array a vector.
Vector
is a java class and people will assume that is what you are using when you name the variablevectorOfInt
.The compiler error you are getting is because the compiler doesn't know that your
Comparator
is operating onInteger
s. Since all it sees is anObject
, it doesn't know that o1 is actually anInteger
and can be unboxed to be anint
. By specifying the comparator type, you provide more information and the conversion can be made implicitly.