In my application I have a RecyclerView
and the user is able to select different kinds of orderings for the items within it. The ordering is based on a Comparator
.
Let's assume the user rotates the device: After the configuration change I want to restore the ordering of the items. I thought about doing it this way:
public interface ItemComparator<T> extends Comparator<T>, Serializable { }
public class TestActivity extends AppCompatActivity {
private static final String KEY_COMP = "COMP";
private ItemComparator<MyItem> comparator;
protected void onCreate(@Nullable Bundle savedState) {
// main setup
if(savedState == null) {
comparator = (a, b) -> a.getName().compareTo(b.getName());
} else {
// unsafe cast here - can I get rid of it?
comparator = (ItemComparator<MyItem>) savedState.getSerializable(KEY_COMP);
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_COMP, comparator);
}
}
Is this valid code or can this cause a memory leak or any other problems?