Arrays, ArrayLists and HashMaps
This presentation will cover three fundamental data structures in Java:
We will explore their characteristics, how to use them, and when to choose one over the other.
Arrays are fixed-size, ordered collections of elements of the same type.
int, String, Object).// Create an array of strings with a size of 5
String[] fruits = new String[5];
// Add elements
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Orange";
// Access an element
String fruit = fruits[1]; // "Banana"
// Remove an element (by setting it to null)
fruits[1] = null;
// Get the size
int size = fruits.length; // 5ArrayList is a dynamic, ordered collection of elements. It is part of the Java Collections Framework.
ArrayList can grow or shrink dynamically.Important
The ArrayList class does not support primitive types directly. To work with primitives like int, you should use wrapper classes (Integer) instead.
import java.util.ArrayList;
// Create an ArrayList of strings
ArrayList<String> vegetables = new ArrayList<>();
// Add elements
vegetables.add("Carrot");
vegetables.add("Broccoli");
vegetables.add("Spinach");
// Access an element
String vegetable = vegetables.get(1); // "Broccoli"
// Remove an element
vegetables.remove(1); // Removes "Broccoli"
// Get the size
int size = vegetables.size(); // 2HashMap is a collection of key-value pairs. It is part of the Java Collections Framework.
HashMap can grow or shrink dynamically.Important
The HashMap class does not support primitive types directly. To work with primitives like int, you should use wrapper classes (Integer) instead.
import java.util.HashMap;
// Create a HashMap with String keys and Integer values
HashMap<String, Integer> ages = new HashMap<>();
// Add elements
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Charlie", 35);
// Access an element
int age = ages.get("Bob"); // 25
// Remove an element
ages.remove("Charlie");
// Get the size
int size = ages.size(); // 2| Feature | Array | ArrayList | HashMap |
|---|---|---|---|
| Size | Fixed | Dynamic | Dynamic |
| Ordering | Ordered | Ordered | Unordered |
| Indexing | Integer index (0-based) | Integer index (0-based) | Key (Object) |
| Storage | Primitives and Objects | Objects only | Objects only (Key-Value pairs) |
| Performance | Fast for access, slow for resizing | Slower access, flexible resizing | Fast for key-based access |
Choosing the right data structure is crucial for writing efficient and maintainable Java code.