Search code examples
javaandroidclasscastexception

HTC M8 (6.0.1): TreeSet<Long>.contains(Long) throws class cast exception: "cannot cast Double to Long"


We've just received a crash report that I honestly don't understand, and I'm not even sure if it's a good question as such... but I can't think of anything.

I have the following code:

public class LeisureEventSelectedCategories {
    private Set<Long> ids = new TreeSet<>();

    public boolean contains(Long id) {
        if (id == null) {
            return false;
        }
        return ids.contains(id);
    }

Where the line return ids.contains(id) crashes with the following exception:

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Long
    at java.lang.Long.compareTo(Long.java)
    at java.util.TreeMap.find(TreeMap.java)
    at java.util.TreeMap.findByObject(TreeMap.java)
    at java.util.TreeMap.containsKey(TreeMap.java)
    at java.util.TreeSet.contains(TreeSet.java)
    at com.acme.b.a.d.a(LeisureEventSelectedCategories.java:50)

The Long I receive here is from a Map<String, Long>.

leisureEventSelectedCategories.contains(eventCategoryNameToEventId.get(categoryName)) || leisurePlaceSelectedCategories.contains(placeCategoryNameToPlaceId.get(categoryName)),

Where

Map<String, Long> placeCategoryNameToPlaceId = new LinkedHashMap<>();
Map<String, Long> eventCategoryNameToEventId = new LinkedHashMap<>();

Apart from replacing the TreeSet with a HashSet and using Collections.sort() where I need it, what could be causing this and how should I avoid it in the future?

EDIT:

image of values in leisureEventSelectedCategories after selecting all items that come from server:

LeisureEventSelectedCategories values

image of values in eventCategoryNameToPlaceId

eventCategoryNameToEventId values


Solution

  • In the end, we just replaced it with LinkedHashSet<Long> and the crash is gone.