Reputation: 183
I am doing this assignment where we have to create 2 types of object,
public class Person implements Cloneable, Comparable<Person>
and
public class Book implements Cloneable, Comparable<Book>
The main task of this program is to sort the two types using its own compare functions as following:
compareTo(Person o)
compareTo(Book o)
So, I created 2 ListArray as following in the main function to store the book and person objects as following:
List<Book> bookArray = new ArrayList<Book>();
List<Person> peopleArray = new ArrayList<Person>();
And I have my sorting algorithm implemented in another class like the following:
public class Sort{
Comparable<Object>[] values;
public Sort(List<Object> inputArray) {
this.values = (Comparable<Object>[]) inputArray.toArray();
}
public doSort() {
//sort implementation...
}
The problem is when calling this function using the arrays above
Sort sorter = new Sort(peopleArray);
sorter.doSort();
Eclipse shows the error saying "The constructor Sort(List) is undefined." What am I doing wrong here? Thank you in advance.
Upvotes: 1
Views: 1243
Reputation: 401
Its not so clear but If am right Whenevr you use another new class for sorting that is probably implements COMPARATOR.
so in ur example Sort class should be
Class Sort implemets Comaparator<Person> {
public void Compare(Object 01,Object 02) {
return (Person)o1.comapareTo(Person)o2;
}
then in main
, call
Collections.sort(list,new Sort());
lly u need to do for book too.
Upvotes: 0
Reputation: 425168
Just because you named the field "personArray" does not make it an array - you are passing in a List
when the constructor is declared to expect an array.
I recommend that you never use arrays unless you absolutely have to; use Collections instead, because they are so much easier to deal with and, contrary to popular belief, the performance difference is negligible.
If you remove all arrays from your code, and add some generics, it will all work:
public class Sort<T extends Comparable<T>> {
private List<T> values;
public Sort(List<T> values) {
this.values = values;
}
public void doSort() {
Collections.sort(values);
}
}
Note that this whole class adds very little value, if sorting is all it does. Your client code can just code this one line instead:
Collections.sort(values);
Upvotes: 2
Reputation: 803
You can pass any class instance to Object type. but List is not a parent of List. Those are just two different types.
You can say
public Sort(List<? extends Object> inputArray)
so that it will accept any type.
Upvotes: 2