Home » Java » java – Insert removed element in generic list-Exceptionshub

java – Insert removed element in generic list-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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?

How to&Answers:

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

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