java - 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?
解决方案
Get rid of the wildcard; and I don't even think you need a bound:
private void <T> removeElement(int i, List<T> objects) {
推荐阅读
- python - 将json转换为python中的对象,以数字为键
- c# - 从 IList 中删除 IWebElement
基于 IWebElement 中的文本 - c# - 为什么我在 FluentValidation MustAsync 中收到 CS1061 错误
- python - 调用 API 调用时 tkinter 中的对话框冻结
- javascript - 无法将 Mongoose 连接到 Mongodb 连接 ECONNREFUSED ::1:27017
- c - C中结构的不完整类型定义的无效使用
- linux - Linux bash:如何根据另一行/不同行上的模式替换一行上的字符串?
- postgresql - 未找到 PostgreSQL ODBC 连接 VB .NET 数据源名称且未指定默认驱动程序
- python - 在熊猫中,如何将给定列的不同值转置到行的不同列
- c - 输出未包含所有字符