0

arrayList をソートするプログラムを作成していますが、add 関数をオーバーライドするたびに、次のメッセージが表示されます。互換性のない戻り値の型を使用しようとしています: void が必要です: 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);
    }
}
4

3 に答える 3

0

参考までに、コンポジションと継承を同時に使用しようとしているようです。デリゲート"a"で指定された文字列を比較しているが、super.add()を呼び出しているため、addメソッドは機能しません。追加する文字列がリストの最後の文字列である場合、または最初に追加された文字列の場合も、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;
}
于 2011-04-07T04:12:15.073 に答える
0

エラーメッセージを見れば一目瞭然ですが、

add メソッドは値 true のブール値を返す必要があります。こちらの Java ドキュメントを参照してください

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). 
于 2011-04-04T04:33:57.023 に答える
0

これはあなたに言っているようです:

変化する public void add(String x)

public boolean add(String x)

[実際にブール値を返すようにする]

于 2011-04-04T04:33:58.293 に答える