incompatible types : ArrayList<Link> cannot be converted to Links<Link>

61 views Asked by At

I'm trying to instanciate an abstract class and it doesn't work.

abstract class Links<T> implements List<T>{
    
}

Links<Link> notVisitedLinks = new ArrayList<Link>();

I also tested the Links class as not an abstract class and it tells me the following error message :

Links is not an abstract class and it doesn't override abstract method subList(int, int) in List

class Links<T> implements List<T>{
    
}

Links<Link> notVisitedLinks = new ArrayList<Link>();

I tried to undersand how to override the subList method but I did'nt succeed.

1

There are 1 answers

0
AndresPolo On

You're getting an error because ArrayList doesn't match up with Links. Even though ArrayList fits with List, it's not quite the same as Links, even though Links expands List.

One fix could be making a regular class that expands Links and adds the needed methods. Like this:

import java.util.ArrayList;
import java.util.List;

abstract class Links<T> implements List<T> {

}

class ConcreteLinks<T> extends Links<T> {
    private List<T> list = new ArrayList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    // Add the other methods from the List interface here

    @Override
    public T get(int index) {
        return list.get(index);
    }

    @Override
    public T set(int index, T element) {
        return list.set(index, element);
    }

    // Add the other methods from the List interface here

    @Override
    public void add(int index, T element) {
        list.add(index, element);
    }

    @Override
    public T remove(int index) {
        return list.remove(index);
    }

    // Add the other methods from the List interface here
}

public class Main {
    public static void main(String[] args) {
        ConcreteLinks<Link> notVisitedLinks = new ConcreteLinks<>();
        notVisitedLinks.add(new Link());
        // Now you can use notVisitedLinks as a list of Link objects
    }
}

In this code:

ConcreteLinks is a regular class that extends Links and fills in the required methods of the List interface. notVisitedLinks is an instance of ConcreteLinks, so you can treat it like a list of Link objects.