Search code examples
javaabstract-classtype-conversionabstract-data-type

Copying List Type to an Abstract List


I have two classes that inherit from a single abstract class. The two classes dictate which type of AbstractList to use, either and ArrayList or LinkedList.

public class ArrayListMergeSort extends MergeSortData
{
public ArrayListMergeSort()
   {
    super();
    data= new ArrayList<String>();
   }
}

I was wondering how I would be able to make a new temporary AbstractList in the abstract class based on which type of list data is?


Solution

  • You could have an abstract method returning a List in the abstract class MergeSortData :

    public abstract List<String> getNewList();
    

    Then, you implement this method in each sub-class.

    For example, in ArrayListMergeSort :

    public List<String> getNewList() {
        return new ArrayList<String>();
    }
    

    Any method of the abstract class MergeSortData can then call getNewList() to obtain a new List of the correct implementation.