How does the Android activity lifecycle work? Explain how you would handle configuration changes, such as screen rotations, without losing user data or state.
Java’s type erasure mechanism in generics ensures compatibility with older Java versions by removing generic type information during compilation. This process involves replacing all generic type parameters with their bounds (or `Object` if unbounded) and inserting necessary casts for type safety. FoRead more
Java’s type erasure mechanism in generics ensures compatibility with older Java versions by removing generic type information during compilation. This process involves replacing all generic type parameters with their bounds (or `Object` if unbounded) and inserting necessary casts for type safety. For example, a generic class like `Box<T>`:
public class Box<T> {
private T item;
public void set(T item) { this.item = item; }
public T get() { return item; }
}
after type erasure, it becomes:
public class Box {
private Object item;
public void set(Object item) { this.item = item; }
public Object get() { return item; }
}
To avoid `ClassCastException` and ensure type safety, follow these guidelines:
1. Bounded Type Parameters: Limit types with bounds to ensure correct usage.
public class NumberBox<T extends Number> { … }
2. Use Generics with Collections: Enforce type safety.
List<String> strings = new ArrayList<>();
3. Type Inference with Diamond Operator: Let the compiler infer types.
Box<String> stringBox = new Box<>();
4. Generic Methods: Ensure type-safe operations.
public static <T> void addItemToList(List<T> list, T item) { list.add(item); }
5. Avoid Raw Types: Prevent unsafe casts.
Box<String> box = new Box<>();
By adhering to these practices, you can create type-safe generic classes and methods in Java.
See less
The Android activity lifecycle consists of several states: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). These states manage the activity's creation, visibility, interaction, and destruction. To handle configuration changes like screen rotations without losing user data orRead more
The Android activity lifecycle consists of several states: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). These states manage the activity’s creation, visibility, interaction, and destruction.
To handle configuration changes like screen rotations without losing user data or state, you can use the onSaveInstanceState() and onRestoreInstanceState() methods. onSaveInstanceState() is called before the activity is destroyed, allowing you to save data to a Bundle. onRestoreInstanceState() or onCreate() can then retrieve this data when the activity is recreated.
Alternatively, you can use the ViewModel architecture component, which is designed to store and manage UI-related data in a lifecycle-conscious way. ViewModel objects survive configuration changes, meaning they retain data even if the activity is destroyed and recreated.
See less