开发者

Issues overriding add

I'm writing a program that's supposed to sort an arrayList, but whenever I override the add function, I get this message : "add(Java.lang.String) in SortedList cannot implement add(E) in java.util.List; attempting to use incompatible return type found : void required: boolean"

I'm not really sure what I'm doing wrong. Below is my code. Thanks in advance!

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开发者_JAVA百科.compareTo(a.get(i+1))<=0)
                super.add(x);
    }
}


It's pretty obvious from the error message,

Your add method needs to return a boolean of value true, See the 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). 


This seems to tell you: "add(Java.lang.String) in SortedList cannot implement add(E) in java.util.List; attempting to use incompatible return type found : void required: boolean"

Change public void add(String x)

to

public boolean add(String x)

[Also make it actually return a boolean]


FYI, it looks like you're trying to use composition and mixing it with inheritance at the same time. Your add method won't work because you're comparing the given String in your delegate, "a", but calling a super.add(). You'll also get an ArrayOutOfBoundsException if the String you add should be the last one in the list or if it's the first one added. It should be:

@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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜