Java Collections Framework: Collections & Arrays Classes

📘 Java Learning – Collections Framework (Final Part: Collections Class & Arrays Class) 🚀🎯 Wrapping up my Java Collections journey with two powerful utility classes from java.util package: 👉 Collections class 👉 Arrays class These classes provide utility methods for sorting, searching, reversing, and converting data structures efficiently. 🔰 Collections Class A utility class that provides methods for Collection implemented classes. 📌 Sorting a List Collections.sort(List l); // Natural sorting Collections.sort(List l, Comparator c); // Custom sorting ✔ Elements must be homogeneous & Comparable (for natural sorting) ✔ Null elements not allowed (NullPointerException) 📌 Searching in a List Collections.binarySearch(List l, Object obj); Collections.binarySearch(List l, Object key, Comparator c); ⚠ Important Rules: • List must be sorted before searching • Uses Binary Search algorithm • Successful search → returns index • Unsuccessful search → returns insertion point • Must use same Comparator used for sorting 📌 Reversing a List Collections.reverse(List l); // Reverses list Collections.reverseOrder(); // Returns Comparator (descending) ✔ reverse() → works on List ✔ reverseOrder() → returns Comparator 🔰 Arrays Class Utility class for array operations (primitive & object arrays). 📌 Sorting Arrays Arrays.sort(int[] arr); // Primitive (natural order) Arrays.sort(Object[] arr); // Natural order Arrays.sort(Object[] arr, Comparator c); // Custom sorting ✔ Primitive arrays → only natural sorting ✔ Object arrays → natural or custom sorting 📌 Searching in Arrays Arrays.binarySearch(int[] arr, key); Arrays.binarySearch(Object[] arr, key); Arrays.binarySearch(Object[] arr, key, Comparator c); ✔ Same rules as Collections.binarySearch() 🔰 Converting Array to List List list = Arrays.asList(Object[] arr); ⚠ Important: • Creates a List view, not independent list • Changes in list reflect in array & vice versa • Cannot change size (add/remove → UnsupportedOperationException) • Replacement allowed but type must match (else ArrayStoreException) 🧪 Combined Example Integer[] arr = {30, 10, 20}; Arrays.sort(arr); // Sorting array System.out.println(Arrays.toString(arr)); // [10, 20, 30] int index = Arrays.binarySearch(arr, 20); System.out.println(index); // 1 List list = Arrays.asList(arr); Collections.reverse(list); System.out.println(list); // [30, 20, 10] ⭐ Final Takeaways • Collections → Utility methods for List • Arrays → Utility methods for Arrays • Always sort before binarySearch • asList() creates a fixed-size list view This completes my Java Collections Framework journey 🎯 Understanding these utilities makes data handling more efficient and interview-ready 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #CollectionsClass #ArraysClass #JavaCollections #LearningJourney

To view or add a comment, sign in

Explore content categories