In this follow-up post, we’ll focus entirely on Generics in Collections, the concept of type safety in Java collections, and how generics make your code more flexible and robust. Additionally, we’ll explore how sorting works with generic collections and some advanced utility methods that come in handy.
—
—
Generics in Java allow you to write a class, interface, or method that works with any data type. By using generics with collections, you ensure type safety at compile time. This means you can avoid potential ClassCastException errors and eliminate the need for explicit casting.
For example:
List<String> strings = new ArrayList<>(); strings.add("Hello"); // Adding a non-String value will now cause a compile-time error.
Generics ensure that only the specified data type can be stored in the collection, preventing runtime issues and making code more readable and maintainable.
—
Generics in lists ensure that you can only store objects of the specified type. For example, List
import java.util.ArrayList; import java.util.List; public class GenericListExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); // The following line would cause a compile-time error: // names.add(123); // Error: cannot add Integer to List<String> for (String name : names) { System.out.println(name); } } }
—
Sets with generics work similarly to lists, ensuring that all elements are of a specific type.
import java.util.HashSet; import java.util.Set; public class GenericSetExample { public static void main(String[] args) { Set<Integer> numbers = new HashSet<>(); numbers.add(10); numbers.add(20); numbers.add(30); // Compile-time error if a non-Integer is added: // numbers.add("forty"); // Error for (Integer num : numbers) { System.out.println(num); } } }
—
Maps, being key-value pairs, support generics for both the key and the value. For example, Map
import java.util.HashMap; import java.util.Map; public class GenericMapExample { public static void main(String[] args) { Map<String, Integer> phoneBook = new HashMap<>(); phoneBook.put("Alice", 12345); phoneBook.put("Bob", 67890); // The following would cause a compile-time error: // phoneBook.put(123, "Charlie"); // Error for (Map.Entry<String, Integer> entry : phoneBook.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
—
Sorting generic collections is straightforward and is done using Collections.sort() for lists and Comparable or Comparator for custom sorting.
List<String> strings = new ArrayList<>(); strings.add("Hello"); // Adding a non-String value will now cause a compile-time error.
For custom sorting, you can implement the Comparator interface.
—
The Collections utility class also supports operations such as binary search, shuffle, reverse, and frequency counting. These operations can be applied to generic collections for more powerful data manipulation.
import java.util.ArrayList; import java.util.List; public class GenericListExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); // The following line would cause a compile-time error: // names.add(123); // Error: cannot add Integer to List<String> for (String name : names) { System.out.println(name); } } }
—
import java.util.HashSet; import java.util.Set; public class GenericSetExample { public static void main(String[] args) { Set<Integer> numbers = new HashSet<>(); numbers.add(10); numbers.add(20); numbers.add(30); // Compile-time error if a non-Integer is added: // numbers.add("forty"); // Error for (Integer num : numbers) { System.out.println(num); } } }
—
Implement a simple stack class using generics. The stack should support pushing elements, popping elements, and checking if it’s empty.
Create a List of custom objects, such as Person, and sort it based on a custom field like age or name.
—
In this post, we explored how to use Generics in Collections for type safety, flexibility, and ease of use. We also discussed sorting and advanced utility methods that make working with collections more efficient. By mastering generics, you can write more robust, error-free code that is also highly reusable.
—
The above is the detailed content of Part Generics in Collections, Sorting, and Utility Methods. For more information, please follow other related articles on the PHP Chinese website!