0

I wanted to make a generic method for appending a copy of two linked list together and putting it in another linked list. list a and list b in list c.

here is the code that I have so far.

public static LinkedSequence<?> concatenaton(LinkedSequence<?> s1, LinkedSequence<?> s2) throws java.lang.NullPointerException
{
    // Create a new sequence that contains all the elements from one sequence followed by another.
    LinkedSequence<?> concat = new LinkedSequence();
    if(s1 == null || s2 == null) {
        return null;
    }
    else {
        LinkedSequence h1;
        LinkedSequence h2;
        h1 = s1.clone();
        h2 = s2.clone();
        concat.addAll(h1);
        concat.addAll(h2);
    }
    return concat;


}

public LinkedSequence<T> clone() {
    // Generate a copy of this sequence.
    LinkedSequence<T> copy = new LinkedSequence<T>();
    //Node<T> newNode = new Node<T>(element);
    Node<T> curr = first;
    if(getCurrent() == null) {
        return null;
    } else {
        while(curr != null) { //iterate through current list
            copy.addLast(curr.getValue());
            curr = curr.getLink();
        }
    }
    return copy;
}

public void addLast(T element) {
    Node<T> newNode = new Node<T>(element);
    if (isCurrent() == false) {
        current = newNode;
        first = newNode;
        last = newNode;
    }
    else {
        //Node newNode = new Node(element);
        last.setLink(newNode);
        last = newNode;
    }
}

the clone copies the whole list in a new list. I keep getting an error saying that I make a generic type in a static type.

jam
  • 5
  • 3

1 Answers1

0

One thing is for sure... you need to use a type-parameter in your concat static method to impose the constraint that both input sequences have the same element type like so:

public static <E> LinkedSequence<E> concat(LinkedSequence<E> s1, LinkedSequence<E> s2) {
    if(s1 == null || s2 == null) {
        return null;
    }
    LinkedSequence<E> concat = new LinkedSequence<>();
    concat.addAll(s1);
    concat.addAll(s2); 
    return concat;
}

I took the liberty of edit the code a bit removing what seem to be redundant or inefficient.

You can make it a bit more general and accept inputs that contains type that are subclasses of the return type:

public static <E> LinkedSequence<E> concat(LinkedSequence<? extends E> s1, LinkedSequence<? extends E> s2) { ... }

You probably will need to change the addAll definition to accept ? extends E rather than E typed input collections.

Valentin Ruano
  • 2,726
  • 19
  • 29