I want to sort out my Arraylist<Book> b on the values returned by the method numPoints() in class Book. show() is a method of class Book, that prints out the code.
Everything else works okay, just the method sort() is the problem i think.
public class som {
private static ArrayList<Book> b;
public static void main(String[] args) {
b = new ArrayList<Book>();
...
}
...
public static void sort() {
Book mon = null;
int indMax = 0;
for(int i=0; i<b.size()-1; i++){
mon = b.get(i);
indMax = i;
for(int j=i+1; j<b.size(); j++){
if(b.get(j).numPoints() > mon.numPoints()){
mon = b.get(j);
}
}
if(indMax != i){
b.set(indMax, b.get(i));
b.set(i, mon);
}
}
for(int s=0; s<b.size(); s++) {
b.get(j).show();
}
}
class Book {
...
public double numPoints() {
...
}
public void show() {
...
}
...
}
i also tried the following code, but neither of them work properly.
public static void sort() {
ArrayList<Book> o = new ArrayList<Book>();
double vMax=0;
int iMax=0;
while(b.size()!=0) {
for(int i = 0; i<b.size(); i++) {
if(vMax<b.get(i).numPoints()) {
vMax=b.get(i).numPoints();
iMax=i;
}
}
o.add(b.get(iMax));
b.remove(iMax);
}
for(int j=0; j<o.size(); j++) {
o.get(j).show();
}
The first one just doesn't work properly, but in the second one terminal prints out :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
can somebody please help me figure out what is wrong?
class Objectis going to be extremely confusing. You should name the class something besidesObject. As to sorting the list, please read the Oracle Java tutorial on "Object Ordering"