0

Is there a way to change the following code for splitting a collection based on the used types to have no unchecked casts?

    public
    static <TYPE, TYPE1 extends TYPE, TYPE2 extends TYPE> void
    split(
            Collection<TYPE> input_list,
            Collection<TYPE1> output_list1,
            Collection<TYPE2> output_list2,
            Class<TYPE1> class1,
            Class<TYPE2> class2) {
        for (TYPE input_elem : input_list) {
            if (input_elem.getClass() == class1) {
                //noinspection unchecked
                output_list1.add((TYPE1) input_elem);
            } else if (input_elem.getClass() == class2) {
                //noinspection unchecked
                output_list2.add((TYPE2) input_elem);
            } else
                throw new RuntimeException();
        }
    }
  • 1
    Don't forget, a `Collection` may include subclasses of `TYPE1`, so you can't check the class with == (and you probably should be using `equals` anyway). – Andy Turner Aug 19 '21 at 18:42

1 Answers1

2

Regarding the answer from Test if object is instanceof a parameter type

Id suggest

for (TYPE input_elem : input_list) {
    if (class1.isInstance(input_elem)) {
        output_list1.add(class1.cast(input_elem));
    } else if (class2.isInstance(input_elem)) {
        output_list2.add(class2.cast(input_elem));
    } else {
        throw new RuntimeException();
    }
}
azro
  • 53,056
  • 7
  • 34
  • 70