Arrays and collections are data structures that can store multiple values in a single variable. They are useful when you need to work with multiple values of the same type.
Arrays:
– Arrays are fixed in size and have a specific order.
– You can access individual elements with an index.
– Arrays can be resized by creating a new array and copying the elements from the old array to the new one.
– Arrays can store both primitive types (int, char, etc.) and objects.
Example:
“`
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
String[] names = {“John”, “Jane”, “Alice”}; // Array of strings
System.out.println(numbers[0]); // Output: 1
System.out.println(names[2]); // Output: Alice
“`
Collections:
– Collections are dynamic and can grow or shrink in size.
– Collections have different implementations like List, Set, and Map.
– Collections can store objects and provide additional functionality like sorting, searching, and filtering.
– Collections provide methods for adding, removing, and accessing elements.
Example:
“`
List
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println(numbers.get(1)); // Output: 2
Set
names.add(“John”);
names.add(“Jane”);
names.add(“Alice”);
System.out.println(names.contains(“Jane”)); // Output: true
“`
Arrays and collections have different use cases. Arrays are useful when you need a fixed-size collection, while collections are useful when you need a dynamic collection with additional functionality.