user3671459
user3671459

Reputation: 455

Arraylist and InsertionSort Object

Question

I need to use Insertionsort to sort my ArrayList of <klant> on an element (Achternaam). How do i do that?

Code

The code im using for insertion sort gives me a few errors because i am using a Arraylist instead of the 1000's of examples with array's.

public class InsertionSort {

public static void insertionSort(ArrayList<Klant> klanten){
    for(int i = 1; i <klanten.size(); i++){
        Comparable objectToSort = klanten.get(i);
        int j = i;
        while(j > 0 && klanten[j-1].compareTo(objectToSort) > 1){
            klanten[j] = klanten[j-1];
            j--;
        }
        klanten[j] = objectToSort;
    }
}
}

The Klant.class has several getters and setters which return its variables one of them is getAchternaam() which returns the achternaam String.

calling the code:

ArrayList<Klant> klanten = new ArrayList<Klant>();
InsertionSort stringsort = new InsortionSort();
stringsort.insertionSort(klanten);

What am i doing wrong and how can i fix it?

Everywhere in the code insertionSort.class at klanten is a error

'The type expression must be an array but it resolved to ArrayList < klant>

Upvotes: 0

Views: 3027

Answers (2)

khelwood
khelwood

Reputation: 59239

With an array you can examine and assign elements using the [] operator. With a List you need to use get and set methods.

So, where you want to assign an object to a position in the list, you use:

klanten.set(index, object);

and where you want to get an object from a position in the list, you use:

klanten.get(index);

Edit:

Also compareTo(...) > 1 is wrong. The only significance of a compareTo return value is if it is greater, less than or equal to zero. Comparing it to 1 is not going to help your sorting.

Upvotes: 1

Roger
Roger

Reputation: 11051

Can you confirm that you are importing the correct version of InsertionSort instead of an old class that was taking in an Array? If you are using an IDE mouse over insertionSort in stringsort.insertionSort(klaten); and you should see what it is expecting.

Make sure all of your files are saved.

Also I recommend making insertionSort take in a List and instantiating your list as: List<Klant> klanten = new ArrayList<Klant>();

Upvotes: 0

Related Questions