Pergunta

How to add String[] into Set avoiding exception. I put array's size to 100, it doesn't need to be fixed size array but I need to have access to array's members like x[] so i can insert array values.

Set<String[]> s = new TreeSet<String[]>();
String[] x = new String[100];
int i=0;
x[i++] = ...
x[i++] = ...
s.add(x);



Ljava.lang.String; cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)  
Foi útil?

Solução

Arrays don't have a "natural order", that's why you got this exception.

One way is to provide a custom comparator when constructing your TreeSet.

Set<String[]> s = new TreeSet<String[]>(new Comparator<String[]>() {    
        @Override
        public int compare(String[] o1, String[] o2) {
             //your logic here
        }
    });

But I don't think you should use a TreeSet for that sort of things because that will be hard to tell how to define an order for comparing your arrays.

IMO your best option is to create a wrapper class, overriding hashcode and equals and put those in an HashSet.

class WrapperStringArray {
    private String[] arr;

    //constructors, getters, setter and additional methods

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(arr);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        WrapperStringArray other = (WrapperStringArray) obj;
        return Arrays.equals(arr, other.arr);
    }   
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top