I am trying to sort an ArrayList full of customer objects.
ArrayList Cust = new ArrayList();
Cust.add(new Customer("John",15,"New York",200));
Cust.add(new Customer("Moya",25,"Randfontein",200));
Cust.add(new Customer("Sue",44,"Jersey",100));
Cust.add(new Customer("Mpho",23,"London",250));
I have a foreign class, Sort that contains an insertion sort method that implements the Comparable interface.
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(ArrayList<AnyType> a) {
for (int p = 1; p < a.size(); p++) {
AnyType tmp = a.get(p);
int j;
for (j = p; j > 0 && tmp.compareTo(a.get(j - 1)) < 0; j--) {
a.set(j, a.get(j - 1));
}
a.set(j, tmp);
}
I tried using this method in the main class to sort the ArrayList based on the Customer's age(second element).
Sorting.insertionSort(CustList);
This gives me an error though: no suitable method found for insertionSort(java.util.ArrayList) Sorting.insertionSort(CustList);
Help me ¯_(ツ)_/¯
as requested, Here is the full code :
public interface Comparator<AnyType> {
/**
* Return the result of comparing lhs and rhs.
* @param lhs first object.
* @param rhs second object.
* @return < 0 if lhs is less than rhs,
* 0 if lhs is equal to rhs,
* > 0 if lhs is greater than rhs.
*/
int compare( AnyType lhs, AnyType rhs );
}
///
public final class Customer implements Comparable<Customer> {
String name;
int age;
String city;
int loyaltyPoints;
public Customer(String n, int a, String c, int lP) {
name=n; age=a; city=c; loyaltyPoints=lP;
}
public String toString() {
return "Customer " + name + " from " + city + " is " + age + " years old, and has loyaltypoints of " + loyaltyPoints;
}
public int compareTo(Customer rhs) {
return this.age - rhs.age;
}
}
///
public final class Sorting {
public static <AnyType> void insertionSort(ArrayList<AnyType> a, Comparator<? super AnyType> cmp) {
}
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(ArrayList<AnyType> a) {
for (int p = 1; p < a.size(); p++) {
AnyType tmp = a.get(p);
int j;
for (j = p; j > 0 && tmp.compareTo(a.get(j - 1)) < 0; j--) {
a.set(j, a.get(j - 1));
}
a.set(j, tmp);
}
}
}
///
public class Test{
public static void main(String[] args) {
// Add some customers to an arraylist
ArrayList Cust = new ArrayList();
Cust.add(new Customer("John",45,"Tokyo",200));
Cust.add(new Customer("Johna",25,"London",200));
Cust.add(new Customer("James",33,"New York",100));
Cust.add(new Customer("Jack",23,"Utah",250));
Cust.add(new Customer("Janet",25,"Jersey",250));
Cust.add(new Customer("Jared",28,"Gotham",250));
Sorting.insertionSort(Cust);
}
}