Skip to content
Advertisement

Implementing List interface for CustomList in Java

I need to create a custom list that adds elements in pairs. I copied a similar implementation and adjusted it as needed, but unfortunately, it doesn’t work.

class PairStringList implements List<String> {

    private List list;

    public PairStringList() {
        list = new ArrayList();
    }

    @Override
    public boolean add(String s) {
        list.add(list.size(), s);
        list.add(list.size(), s);
        return true;
    }

//other methods
}

And I have this for testing my code so far.

public static void main(String[] args) {
        List<String> list = new PairStringList();
        list.add("1");
        list.add("2");
        list.add("3");

        for(int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println(s);
        }

        list.add(4, "0");

        for(int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

The problem is that when I call add method the size of the list increases by 2 as it should, but nothing is added and I get an array full of nulls.

Advertisement

Answer

You must have to implement get(int index) method in your PairStringList. Currently your get method is simply returning null. Implementation of get(int index) method should be as shown below:

@Override
public String get(int index) {
    return list.get(index);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement