我正在编写一个应该对arrayList进行排序的程序,但每当我覆盖add函数时,我都会收到以下消息:“SortedList中的add(Java.lang.String)”无法在java.util中实现add(E) .List;尝试使用不兼容的返回类型:void required:boolean“
我不确定我做错了什么。以下是我的代码。提前谢谢!
import java.util.ArrayList;
import java.util.List;
import java.lang.String;
public class SortedList extends ArrayList<String>
{
private ArrayList<String> a;
public SortedList()
{
super();
}
public SortedList(int cap)
{
super(cap);
}
public void add(String x)
{
for(int i=0; i<a.size(); i++)
if(x.compareTo(a.get(i))>=0 && x.compareTo(a.get(i+1))<=0)
super.add(x);
}
}
答案 0 :(得分:0)
从错误消息
中可以看出这一点您的add方法需要返回值为true的布尔值,请参阅java doc here
public boolean add(Object o)
Appends the specified element to the end of this list (optional operation).
Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.
Specified by:
add in interface Collection
Parameters:
o - element to be appended to this list.
Returns:
true (as per the general contract of the Collection.add method).
答案 1 :(得分:0)
这似乎告诉你:“SortedList中的add(Java.lang.String)无法在java.util.List中实现add(E);尝试使用不兼容的返回类型:void required:boolean”
更改
public void add(String x)
到
public boolean add(String x)
[也让它实际返回一个布尔值]
答案 2 :(得分:0)
仅供参考,看起来您正在尝试使用合成并同时将其与继承混合使用。你的add方法不起作用,因为你比较代理中的给定字符串“a”,但调用super.add()。如果您添加的String应该是列表中的最后一个,或者它是添加的第一个,您还将获得ArrayOutOfBoundsException。它应该是:
@Override
public boolean add(String x) {
boolean added = false;
for(int i=0; i<(a.size()-1); i++) {
if(x.compareTo(a.get(i))>=0 && x.compareTo(a.get(i+1))<=0) {
a.add(i, x);
added = true;
break;
}
}
// String is either the first one added or should be the last one in list
if (!added) {
a.add(x);
}
return true;
}