0
public class UniquesDupes
{
    private ArrayList<String> list;

    public UniquesDupes(String input)
    {
        list = new ArrayList<String>();

        String[] words = "abc cde fgh ijk".split(" ");
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(words));
    }


    public Set<String> getUniques()
    {
        Set<String> uniques = new TreeSet<String>();

        for(String a:list)
        {
            uniques.add(a);
        }

        return uniques;
    }

getuniques 不起作用,它编译并运行,但它没有添加到树集中,我不知道为什么

4

2 回答 2

1

假设其他事情正常,

您正在方法范围内创建另一个变量列表,

更改ArrayList<String> list = new ArrayList<String>(Arrays.asList(words));

this.list = new ArrayList<String>(Arrays.asList(words));

引用私有变量list

于 2013-09-21T19:47:39.740 回答
1
ArrayList<String> list = new ArrayList<String>(Arrays.asList(words));

此行创建一个新变量,名为,它与您的原始变量list无关。list

你要

list = new ArrayList<String>(Arrays.asList(words));

甚至

list.addAll(Arrays.asList(words));
于 2013-09-21T19:47:44.087 回答