最小限の作業例を次に示します。
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
class MyClass {
int bandWidth;
int imageSize;
int VmCount;
public MyClass(int bandWidth, int imageSize, int VmCount) {
this.bandWidth = bandWidth;
this.imageSize = imageSize;
this.VmCount = VmCount;
}
}
class MyComparator implements Comparator<MyClass> {
public int compare(MyClass object1, MyClass object2){
return object2.bandWidth - object1.bandWidth; // sort the list in descending order
//return object1.bandWidth - object2.bandWidth; // sort the list in ascending order
}
}
public class Test {
public static void main(String[] args) {
List<MyClass> objects = new LinkedList<>();
objects.add(new MyClass(1,2,3));
objects.add(new MyClass(3,2,3));
objects.add(new MyClass(2,2,3));
Collections.sort(objects, new MyComparator());
for (MyClass object: objects) {
System.out.println(object.bandWidth);
}
}
}
このコード行を完全に理解していないため:
return object2.bandWidth - object1.bandWidth;
別の方法で実装してみましょう。
if (object2.bandWidth > object1.bandWidth) {
return 1; //it can be any positive number
} else if (object2.bandWidth == object1.bandWidth){
return 0;
} else {
return -1; //it can be any negative number
}