首页 > 解决方案 > Insert removed element in generic list

问题描述

I want to remove remove element from the end of ArrayList and set it in the position i. I don't care about order of the elements but i want this operation to be O(1).

My code:

    private void removeElement(int i, List<? extends MyClass> objects) {
        if (i >= objects.size() - 1) {
            objects.remove(objects.size() - 1);
        } else {
            objects.set(i, objects.remove(objects.size() - 1));
        }
    }

By doing this i'm removing object at i index from my ArrayList in O(1) time complexity.

My problem is that Java won't let me set removed element in i position. I'm getting:

Wrong 2nd argument type. Found '? extends MyClass', required '? extends MyClass'.

I know about "producer extends consumer super" rule. I understand that ? extends MyClass object could be different from exact ? extends MyClass List generic type. But shouldn't it be allowed to insert back element retrieved from the same list?

标签: javagenericscollections

解决方案


Get rid of the wildcard; and I don't even think you need a bound:

private void <T> removeElement(int i, List<T> objects) {

推荐阅读