Arrays and Collections
Understanding Arrays Sorting
Primitive Array Sorting
When sorting primitive arrays, Java provides straightforward methods:
public class PrimitiveArraySorting {
public static void main(String[] args) {
// Integer array sorting
int[] numbers = {42, 11, 7, 23, 5};
Arrays.sort(numbers);
// Sorting a specific range
int[] partialSort = {10, 5, 8, 12, 3};
Arrays.sort(partialSort, 1, 4);
}
}
Object Array Sorting
For object arrays, implement Comparable interface:
class Student implements Comparable<Student> {
private String name;
private int age;
@Override
public int compareTo(Student other) {
return Integer.compare(this.age, other.age);
}
}
public class ObjectArraySorting {
public static void main(String[] args) {
Student[] students = new Student[3];
Arrays.sort(students);
}
}
Collections Sorting Techniques
List Sorting
public class ListSorting {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
Collections.sort(numbers);
// Reverse sorting
Collections.sort(numbers, Collections.reverseOrder());
}
}
Custom Comparator Sorting
public class CustomComparatorSort {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple", "banana", "Cherry");
// Case-insensitive sorting
Collections.sort(fruits, String.CASE_INSENSITIVE_ORDER);
}
}
Data Structure |
Sorting Method |
Time Complexity |
Space Complexity |
Array |
Arrays.sort() |
O(n log n) |
O(log n) |
List |
Collections.sort() |
O(n log n) |
O(log n) |
Sorting Flow Visualization
graph TD
A[Unsorted Data] --> B{Sorting Algorithm}
B --> C{Comparison}
C --> D[Swap Elements]
D --> E{Fully Sorted?}
E --> |No| C
E --> |Yes| F[Sorted Data]
Advanced Sorting Considerations
Immutable Collections
- Use
Collections.unmodifiableSortedList()
for read-only sorted lists
- Prevents modification after sorting
Practical Tips
- Always use generics for type-safe sorting
- Implement custom comparators for complex sorting logic
- Consider performance for large datasets
Learning with LabEx
Enhance your sorting skills by practicing interactive Java sorting challenges on the LabEx platform, which provides comprehensive coding exercises.