Re: Collection.sort problem
I haven't used Comparable extensively, but I'll provide what help I can.
The line where you are sorting is this, correct:
If so, you seem to be attempting to use this version of the Collection's Sort Method:
Quote:
sort
public static <T extends Comparable<? super T>> void sort(List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable, but need not be resizable.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
Parameters:
list - the list to be sorted.
Throws:
ClassCastException - if the list contains elements that are not mutually comparable (for example, strings and integers).
UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
See Also:
Comparable
Confirm this for me and I'll attempt to look into this further.
Re: Collection.sort problem
It is correct, however I see that the error is that i only pass the List to be sorted and not what method to be used with comparable. So it should look something like this:
Pseudo-code:
Code :
Collections.sort(temp, compareTo);
Otherwise I won't be able to sort the books based on title.
from Book.java
Code :
public int compareTo(Book objekt) {
if (objekt.getTitle().compareTo(this.getTitle()) < 0){
return 0;
}else{
return 1;
}
}
So my problem remains, i'm not sure how to implement the code so it tells java to sort with the given compareTo method.
Re: Collection.sort problem
That is incorrect. There are two sort methods in the Collections API:
1:
Quote:
sort
public static <T> void sort(List<T> list,
Comparator<? super T> c)
Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
Parameters:
list - the list to be sorted.
c - the comparator to determine the order of the list. A null value indicates that the elements' natural ordering should be used.
Throws:
ClassCastException - if the list contains elements that are not mutually comparable using the specified comparator.
UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
See Also:
Comparator
2:
Quote:
sort
public static <T extends Comparable<? super T>> void sort(List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable, but need not be resizable.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
Parameters:
list - the list to be sorted.
Throws:
ClassCastException - if the list contains elements that are not mutually comparable (for example, strings and integers).
UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
See Also:
Comparable
Now, there are two different classes that have similar names. 1 is the Comparable Class and the other is the Comparator Class.
From the two methods above, the first uses the Comparator Class and the second uses the Comparable Class.
Now, in Book, you implemented the Comparable Class. Which means you shouldnt use the first method to Compare. Even so, this parameter: Comparator<? super T> c means it requires a Comparator Object, not a method. It is very confusing, I know.
Basically, all Objects can be compared somehow. By implementing the Comparable Class, you have to Override the compareTo method and tell the program how each Object is going to be compared. Once you have specified how you want them compared, you can use the sort method #2, where you send it the List and it uses the indicated compareTo method to sort the List.
Now, if you do not implement the Comparable Class but you still want to compare two Objects, you can create something called a Comparator Object. The Comparator Interface requires you to have a compareTo method and an equals method. Once you have specified those, you can compare your objects. This means you have to use sort method #1, where you send it the List and the Comparator Class that you create, where it uses the indicated compareTo and equals methods to sort the List.
Tell me if that makes sense.
Re: Collection.sort problem
Ah yes this is confusing =/
But since I do use the Comparable class with:
Code :
public class Book implements Comparable<Book>
I can't see the problem by using
Code :
List<Book> temp = cob.remoteSort();
Collections.sort(temp);
...
the "temp" is defined as a List and public static <T extends Comparable<? super T>> void sort(List<T> list) want a list to sort...
Can the problem be that my object consists of Strings and ints etc and when i want to sort by book title it goes wrong there?
I do feel really lost :P
Re: Collection.sort problem
Here is a possibility:
The compareTo method is supposed to return a -1,0,or 1. However, in your compareTo method, you only return a 0 and a 1. I do not know if it will make a difference, but it is worth a try. Attempt to revise your compareTo method to have a condition where it will return -1 (an indication that something is less than something else).
Here is how the compareTo method says it should works:
Where x is the result returned:
x < 0 == Object is Less Than Parametrized Object
x = 0 == Object is Equal To Parametrized Object
x > 0 == Object is Greater Than Parametrized Object
Re: Collection.sort problem
Don't create your own collection class, there's already one which exists.
Simply create your list of comparable objects and pass them to your algorithm.
Here's a simple example:
Code Java:
// Book class
// sort books by their name
public class Book implements Comparable<Book>
{
public String name;
public Book(String name)
{
this.name = name;
}
public String toString()
{
return name;
}
public int compareTo(Book other)
{
return this.name.compareTo(other.name);
}
}
Code Java:
public class TestSort
{
public static void main(String[] args)
{
ArrayList<Book> list = new ArrayList<Book>();
list.add(new Book("Multi-threading"));
list.add(new Book("Intro to Java"));
list.add(new Book("Swing"));
list.add(new Book("AWT"));
list.add(new Book("JNI"));
System.out.println("Unsorted list: " + list);
Collections.sort(list);
System.out.println("Sorted list: " + list);
}
}
Re: Collection.sort problem
Rewrote the comparable code to:
Code :
public int compareTo(Book objekt) {
if (objekt.getTitle().compareTo(this.getTitle()) < 0) {
return 0;
} else if (objekt.getTitle().compareTo(this.getTitle()) > 0) {
return -1;
} else {
return 1;
}
}
And wrote in CollectionOfBooks.java
Code :
private List<Book> Books = new ArrayList<Book>();
public void addBook(Book book) {
Collections.sort(Books);
Books.add(book);
}
So that Books is a List and that as soon as you add a book to the list the list should sort...However it still does not =/
Re: Collection.sort problem
Ah thanks helloworld922! That solved my problem! =)
Now another question, if I wish to search for a title in the arraylist, is there a simple way to do this?
Re: Collection.sort problem
Well, since you already have Book as Comparable, the List.indexOf(Object o) method might work.
(Might work, not sure)
Say you wanted to search for a Book with the title: "Java"
Since your comparing via the Book Name, you could say:
Code java:
//Where List is your List
int bookIndex = List.indexOf(new Book("Java",0,0,0,new ArrayList<Author>());
That creates an arbitrary Book Object, where all we care about is the Book Name, and then garbage collects it after we get our Book Index. This will work, as long as the indexOf method compares based on your compareTo method, and as long as your compareTo method ONLY compares the Book Names. If it doesnt, then it won't work.
Try it and tell me if it works, I'm curious myself.
Re: Collection.sort problem
Quote:
Originally Posted by
aussiemcgr
Well, since you already have Book as Comparable, the List.indexOf(Object o) method might work.
indexOf uses the equals method to retrieve objects from a List. So this will not work unless you override the equals method to enable equality by title. (As stated in the API for List: "More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index. ")
Quote:
Now another question, if I wish to search for a title in the arraylist, is there a simple way to do this?
Iterate over the list and check for string equality.
Code :
for ( int i = 0; i < list.size(); i++ ){
if ( list.get(i).getTitle().equals(searchTitle) ){
return list.get(i);
}
}
Alternatively, you could store a Map of the books keyed by title, which would be much faster but a bit more complex to implement
Re: Collection.sort problem
@copeg - Thanks! that worked like a charm! =)
Re: Collection.sort problem
Quote:
So that Books is a List and that as soon as you add a book to the list the list should sort...However it still does not =/
You can't simply add a new item and assume it will be put in sorted order into your arraylist. There are two options:
1. Re-sort your arraylist.
2. Manually look for where the book needs to be inserted in order to maintain sorted order in your arraylist. This should be simple enough since book already implements comparable, just look for the first spot where the book you're trying to add compared to the book at a given index first becomes positive. If you've reached the end of the list without this being satisfied, you can add it to the end. Otherwise, you need to insert your book into the location index (so the book currently at index would be moved back one).