使用List参数实现泛型方法(Implement generic method with List parameter)

编程入门 行业动态 更新时间:2024-10-28 16:18:15
使用List参数实现泛型方法(Implement generic method with List parameter)

我正在尝试定义然后实现一个抽象的setter,它将List of Objects作为参数。 这是这个简单的想法的要点:

public abstract class MyClass { public abstract void setThings(List<?> things); } public class Bar extends MyClass { private List<String> things; @Override public void setThings(List<String> things) { this.things = things; } }

这是行不通的。 我得到的Method does not override method from its superclass并且both methods have the same erasure, but neither overrides the other 。 我了解后者与删除有关的错误,但即使如此,我也无法弄清楚这样做的正确方法。 我尝试了其他一些,如:

public abstract <T> void setThings(List<T> things);

......以及其他一些人。 我发现其他问题/答案已经接近解决这个问题,但没有一个提供了一个坚实的答案(至少对我来说不是那么清楚)。 我已经阅读了教程 ,但也无济于事。 我错过了什么?

I'm trying to define and then implement an abstract setter which takes a List of Objects as a parameter. Here's the gist of this simple idea:

public abstract class MyClass { public abstract void setThings(List<?> things); } public class Bar extends MyClass { private List<String> things; @Override public void setThings(List<String> things) { this.things = things; } }

That doesn't work. I get Method does not override method from its superclass and both methods have the same erasure, but neither overrides the other. I understand the latter error relating to erasures, but even so I can't figure out the correct way to do this. I've tried some others like:

public abstract <T> void setThings(List<T> things);

...as well as a few others. And I've found other questions/answers on SO that come close to addressing this, but none that have provided a solid answer (at least not that was clear to me). I've read through the tutorials as well to no avail. What am I missing?

最满意答案

所以Java非常正确地告诉你,你还没有实现抽象方法setThings ,它使用List<?>而不是List<T>或List<String> 。 所有这些都是不同的东西。 看到这个问题的详细解释 。

最简单的解决方案是为您的抽象类引入一个泛型:

public abstract class MyClass<T> { public abstract void setThings(List<T> things); } public class SubClass extends MyClass<String> { private List<String> things; public void setThings(List<String> things) { this.things = things; } }

So Java is quite correctly telling you that you haven't implemented the abstract method setThings which takes a List<?> not a List<T> or List<String>. All of these are different things. See this question for a detailed explanation.

The simplest solution is to introduce a generic for your abstract class as well:

public abstract class MyClass<T> { public abstract void setThings(List<T> things); } public class SubClass extends MyClass<String> { private List<String> things; public void setThings(List<String> things) { this.things = things; } }

更多推荐

本文发布于:2023-07-22 03:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1216700.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   方法   List   Implement   parameter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!