搜索字符arraylist某些字符

时间:2015-11-13 17:31:20

标签: java arrays arraylist char

我需要{'a','u','o'}的最终字符数组。但现在错误

  

线程中的异常" main" java.lang.UnsupportedOperationException at   java.util.AbstractList.remove(未知来源)at   xyz.jayakumar.test1.DiffCharArray.main(DiffCharArray.java:67)

Character[] c = {'a','b','c','e'};
Character[] p = {'b', 'c','e','u','o'};
//List<Character> fl = new ArrayList(Arrays.asList(c));
List<Character> fl = Arrays.asList(c);
for(char x : p)
{
System.out.println(x);
if(fl.contains(x))
{
//System.out.println("hello");
fl.remove(x);
}
else
{
fl.add(x);
}
}
System.out.println(fl);

3 个答案:

答案 0 :(得分:1)

List<Character> fl = Arrays.asList(c);这会创建一个由数组支持的List,因此您无法在此列表中添加或删除,请使用 而是List<Character> fl = new ArrayList<Character>(Arrays.asList(c));

答案 1 :(得分:0)

Arrays.asList返回一个不可变集合,你需要将这个集合包装在另一个List中。 new ArrayList(fl)

答案 2 :(得分:0)

Arrays.asList()返回不可变列表。您应取消注释List<Character> fl = new ArrayList(Arrays.asList(c));行并发表评论List<Character> fl = Arrays.asList(c);

       Character[] c = {'a','b','c','e'};
        Character[] p = {'b', 'c','e','u','o'};
        List<Character> fl = new ArrayList(Arrays.asList(c));
        //List<Character> fl = Arrays.asList(c);
        for(char x : p)
        {
        System.out.println(x);
        if(fl.contains(x))
        {
        //System.out.println("hello");
        fl.remove(new Character(x));
        }
        else
        {
        fl.add(x);
        }
        }
        System.out.println(fl);

你应该在remove()方法中传递char的包装器对象,否则该字符的ascii代码将被视为索引。所以会有歧义。