Home > Mobile >  how to pass a list parameter in a constructor in Java?
how to pass a list parameter in a constructor in Java?

Time:09-21

How can I add the List parameter in the insertionSort() contructor so that the run method doesnt have any parameters?

public class insertionSort extends Thread {

public insertionSort() {
  
}

// INSERTION SORT
public static <T extends Comparable<T>> void run(List<T> list) {
    // sort the list using insertion sort
    for (int i = 1; i < list.size(); i  ) {
        T key = list.get(i);
        int j = i - 1;
        // move elements of list that are greater than key, to one position ahead of their current position
        while (j >= 0 && list.get(j).compareTo(key) > 0) {
            list.set(j   1, list.get(j));
            j = j - 1;
        }
        // place element at its correct position
        list.set(j   1, key);
    }
}

}

CodePudding user response:

Note that you've created a static run(List). This method is not related to the instance run() method, and therefore you are not taking advantage of extending Thread. You should make the class generic, and then add a List parameter to the constructor (which is no different than adding a parameter to a method). Then you save the list in a field that can be used later by the instance run() method.

// Notice I changed the name to follow PascalCase, as is standard for classes in Java
public class InsertionSort<T extends Comparable<? super T>> extends Thread {

    private final List<T> list;

    public InsertionSort(List<T> list) {
        this.list = list;
    }

    @Override
    public void run() {
        // perform insertion sort on 'list'
    }
}

And make sure you call start() if you want to start a new thread, not run(). For example:

InsertionSort sort = new InsertionSort(theListInstance);
sort.start(); // start new thread, which calls 'run()' for you

Though I would strongly reconsider if you need to extend Thread here. Typically, the better approach is to implement Runnable instead of extending Thread. Then, if you need a new thread, you can just pass the Runnable to a Thread.

public class InsertionSort<T extends Comparable<? super T>> implements Runnable {

    private final List<T> list;

    public InsertionSort(List<T> list) {
        this.list = list;
    }

    @Override
    public void run() {
        // perform insertion sort on 'list'
    }
}

Then use it:

InsertionSort sort = new InsertionSort(theListInstance);

// if you want to run the sort on the calling thread
sort.run();

// or if you want to run the sort on a new thread
Thread thread = new Thread(sort);
thread.start();
  • Related