-1

I've made an interface Attribute to be implemented by different Enums (as I know a Java-enum is a class actually) representing an attribute:

Interface Attribute:

public interface Attribute {
    void print();
}

Then I made two Enums: Size and Type with the Attribute behaviour:

Enum Size:

public enum Size implements Attribute {
    SMALL, MEDIUM, LARGE;

    @Override
    public void print() {
        System.out.println("I am a size.");
    }
}

Enum Type:

public enum Type implements Attribute {
    SQUARE, CIRCLE, TRIANGLE;

    @Override
    public void print() {
        System.out.println("I am a type.");
    }
}

Then I test the structure within my main class:

public class AttributesTestDrive {
    public static void main(String[] args) {
        Set<Attribute> attributes = new TreeSet<>();
        attributes.add(Size.MEDIUM);
        attributes.add(Type.CIRCLE);
        for (Attribute attribute : attributes) {
            attribute.print();
        }
    }
}

Can anyone explain why I get a java.lang.ClassCastException and how to get rid of this:

Exception details:

at java.lang.Enum.compareTo(Enum.java:180)
at java.lang.Enum.compareTo(Enum.java:55)
at java.util.TreeMap.put(TreeMap.java:568)
at java.util.TreeSet.add(TreeSet.java:255)
LowLevel
  • 1,085
  • 1
  • 13
  • 34

1 Answers1

2

Try using HashSet instead of TreeSet

user1211
  • 1,507
  • 1
  • 18
  • 27