Java sort alphabetically, looks like it should work, but doesn't -



Java sort alphabetically, looks like it should work, but doesn't -

i have calculation in bubble sort equation, doesn't seem working , can figure out why.

this in sort class.

system.out.println("\r" + "in order title"); (int out = 0; out < booklist.size(); out++) { (int in = 0; in < booklist.size() - 1; in++) if (booklist.get(in).gettitle().compareto(booklist.get(in + 1).gettitle()) < 0) { book temp = booklist.get(in); booklist.set(in, booklist.get(in+1)); booklist.set(in+1, temp); } system.out.println(booklist.get(out).gettitle() + " " + booklist.get(out).getrating()); } }

the line...

if (booklist.get(in).gettitle().compareto(booklist.get(in + 1).gettitle()) < 0) {

is believe problem lies. can't seem programme sort list of book alphabetically. know solution? rest of code below.

class: book

public class book { string title; int rating; public book(string ptitle, int prating) { title = ptitle; rating = prating; } public string gettitle() { homecoming title; } public int getrating() { homecoming rating; } public void settitle(string newtitle) { title = newtitle; } public void setrating(int newrating) { rating = newrating; } }

class: library

import java.util.arraylist; public class library { public static void main (string [] args) { arraylist<book> booklist = new arraylist<book>(); book b1 = new book ("huckleberry finn", 5); book b2 = new book ("the great gadsby", 2); book b3 = new book ("harry potter", 3); book b4 = new book ("animal farm", 4); book b5 = new book ("the mist", 1); booklist.add(b1); booklist.add(b2); booklist.add(b3); booklist.add(b4); booklist.add(b5); system.out.println("original sequence"); (int cnt = 0; cnt < videolist.size(); cnt++) { system.out.println(booklist.get(cnt).gettitle() + " " + booklist.get(cnt).getrating()); sort sortobject = new sort(); sortobject.calc(booklist); } } }

you sort collection implementing comparable , compareto method , utilize collections.sort(arraylist);

ex:

public class book implements comparable<book> { string title; ...... public int compareto(book other) { homecoming title.compareto(other.title); } }

now can sort arraylist by: collections.sort(booklist);

java

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -