Junior — Middle
Can you explain what collections in Java are and how they are used?
sobes.tech AI
Answer from AI
Collections in Java are data structures that allow storing and managing groups of objects. They include interfaces and classes such as List, Set, Map, Queue, and others. Collections are used for convenient storage, searching, sorting, and processing of data.
For example:
- List — an ordered list of elements allowing duplicates (e.g., ArrayList).
- Set — a collection of unique elements (e.g., HashSet).
- Map — a key-value mapping (e.g., HashMap).
Example of using ArrayList:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}