writzlpfrimpft
writzlpfrimpft

Reputation: 371

java.lang.ClassCastException; no stacktrace with TreeSet<ItemStack>

I have this method defined:

public static TreeSet<ItemStack> getItems() {
    TreeSet<ItemStack> things = new TreeSet<>();
    things.add(new ItemStack(Material.ACACIA_DOOR));
    return things;
}

I also tried putting multiple things in the TreeSet, it doesn't work either.

Now I have this code part:

TreeSet<ItemStack> things = getItems();

If I run this, nothing happens. If I surround it with try/catch, there seems to be an exception thrown. But if I print the error like that:

} catch (Exception exc) {
    System.out.println("Catched an exception:")
    exc.printStackTrace();
    System.out.println(exc.getMessage());
    System.out.println(exc);
}

There isn't any error / Stacktrace or so coming up. It just says:

[INFO]: Catched an exception:
[WARN]: java.lang.ClassCastException
[INFO]: null
[INFO]: java.lang.ClassCastException

So what is the error, how do I prevent it and why do I get it by casting a TreeSet with ItemSets to a TreeSet with ItemSets?

Upvotes: 2

Views: 1761

Answers (3)

LeoColman
LeoColman

Reputation: 7143

What you can do to solve your situation, and thus guaranteeing your intended behaviour is using a normal list instead of a TreeSet to store your items:

ArrayList<ItemStack> items = new ArrayList<ItemStack>();
items.add(new ItemStack(Material.GRASS);
items.add(new ItemStack(Material.DIRT);
//Items is now a list with 2 ItemStacks inside

for (ItemStack is : items) {
    //Do something
}

In that way you fix your issue. Treeset should be used if you want a certain ordain on your Items, and ItemStacks cannot be ordered normally.

Upvotes: 1

秃德666
秃德666

Reputation: 405

The docs, I think maybe the problem is that the item of TreeSet should implments Comparable or extend 'Comparator'. Hope it can help you out.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140484

Read the Javadoc.

Even if you don't know what you're looking for, hit Ctrl-f, and look for ClassCastException in the page. In the documentation of the constructor you're using, TreeSet(), you'll find:

All elements inserted into the set must implement the Comparable interface. ... If the user attempts to add an element to the set that violates this constraint ..., the add call will throw a ClassCastException.

So, either:

  • make your ItemStack implement Comparable<ItemStack>.
  • Provide a Comparator<ItemStack> to the constructor of the TreeSet.

Upvotes: 0

Related Questions