Step 5 of 6

83% Complete

Real-world Applications

Discover practical uses of ArrayLists in real applications

Why ArrayLists Matter

ArrayLists are one of the most commonly used data structures in real-world applications. Their dynamic sizing, random access, and ease of use make them ideal for many scenarios.

ArrayLists power everything from web applications to database systems. Understanding how to use them efficiently is crucial for every programmer.

1. Game Development - Storing Entities

In game development, ArrayLists store game objects like players, enemies, and items. The dynamic size allows games to add/remove objects during gameplay.

Game Entity Management
public class GameEngine {
private ArrayList<Enemy> enemies = new ArrayList<>();
private ArrayList<Projectile> projectiles = new ArrayList<>();
public void spawnEnemy(Enemy enemy) {
enemies.add(enemy); // Add new enemy
}
public void updateGame() {
// Update all enemies
for (Enemy enemy : enemies) {
enemy.update();
}
// Remove defeated enemies
enemies.removeIf(e -> e.getHealth() <= 0);
// Update all projectiles
for (Projectile p : projectiles) {
p.move();
}
}
public void handleCollisions() {
for (int i = 0; i < projectiles.size(); i++) {
for (int j = 0; j < enemies.size(); j++) {
if (projectiles.get(i).collidesWith(enemies.get(j))) {
projectiles.remove(i);
enemies.remove(j);
}
}
}
}
}

2. E-commerce - Shopping Cart

Shopping carts in online stores use ArrayLists to manage items as customers add and remove products.

Shopping Cart Implementation
public class ShoppingCart {
private ArrayList<CartItem> items = new ArrayList<>();
public void addItem(Product product, int quantity) {
// Check if item already exists
for (CartItem item : items) {
if (item.getProduct().getId() == product.getId()) {
item.increaseQuantity(quantity);
return;
}
}
// New item, add to cart
items.add(new CartItem(product, quantity));
}
public void removeItem(int productId) {
items.removeIf(item -> item.getProduct().getId() == productId);
}
public double calculateTotal() {
return items.stream()
.mapToDouble(item -> item.getPrice() * item.getQuantity())
.sum();
}
public ArrayList<CartItem> getItems() {
return new ArrayList<>(items); // Return copy for safety
}
}

3. Social Media - User Feed

Social media platforms use ArrayLists to store feeds, comments, and notifications.

Social Media Feed
public class UserFeed {
private ArrayList<Post> posts = new ArrayList<>();
private ArrayList<Comment> comments = new ArrayList<>();
public void addPost(Post post) {
posts.add(post); // Most recent posts added first
}
public void addComment(int postId, Comment comment) {
posts.stream()
.filter(p -> p.getId() == postId)
.findFirst()
.ifPresent(p -> p.addComment(comment));
}
public ArrayList<Post> getRecentPosts(int count) {
return new ArrayList<>(
posts.stream()
.limit(count)
.collect(Collectors.toList())
);
}
public void deletePost(int postId) {
posts.removeIf(p -> p.getId() == postId);
}
}

4. File Systems - Directory Listing

File systems use ArrayLists to store lists of files and folders in a directory.

Directory File Listing
public class Directory {
private ArrayList<File> files = new ArrayList<>();
private ArrayList<Directory> subdirectories = new ArrayList<>();
public void listFiles() {
System.out.println("Files in directory:");
for (File file : files) {
System.out.println(" " + file.getName() +
" (" + file.getSize() + " bytes)");
}
}
public void listAllRecursive(String prefix) {
for (File file : files) {
System.out.println(prefix + file.getName());
}
for (Directory dir : subdirectories) {
System.out.println(prefix + dir.getName() + "/");
dir.listAllRecursive(prefix + " ");
}
}
public long getTotalSize() {
long size = files.stream()
.mapToLong(File::getSize)
.sum();
size += subdirectories.stream()
.mapToLong(Directory::getTotalSize)
.sum();
return size;
}
}

5. Data Processing - Batch Operations

ArrayLists are used for collecting and processing data in batches, like database records.

Batch Data Processing
public class DataProcessor {
private ArrayList<Record> records = new ArrayList<>();
private static final int BATCH_SIZE = 1000;
public void processData(String[] rawData) {
// Parse data into records
for (String line : rawData) {
records.add(parseRecord(line));
}
}
public void processBatches() {
for (int i = 0; i < records.size(); i += BATCH_SIZE) {
int end = Math.min(i + BATCH_SIZE, records.size());
ArrayList<Record> batch = new ArrayList<>(
records.subList(i, end)
);
// Process this batch
saveBatchToDatabase(batch);
}
}
public ArrayList<Record> filterRecords(Predicate<Record> condition) {
return records.stream()
.filter(condition)
.collect(Collectors.toCollection(ArrayList::new));
}
}

6. Autocomplete Systems

Search engines and text editors use ArrayLists to store and quickly access suggestions.

Autocomplete Suggestions
public class AutocompleteEngine {
private ArrayList<String> suggestions = new ArrayList<>();
public ArrayList<String> getSuggestions(String prefix) {
return suggestions.stream()
.filter(s -> s.startsWith(prefix))
.limit(10) // Return top 10 suggestions
.collect(Collectors.toCollection(ArrayList::new));
}
public void addSuggestion(String word) {
if (!suggestions.contains(word)) {
suggestions.add(word);
}
}
public void learnFromUser(String query) {
if (!suggestions.contains(query)) {
suggestions.add(query);
// Could sort by frequency for better suggestions
}
}
}

Performance Tips for Real Applications

✓ Pre-allocate if size is known

// Good: Pre-allocate capacity
ArrayList<Item> items = new ArrayList<>(5000);
for (int i = 0; i < 5000; i++) {
items.add(new Item(i));
}

✓ Use removeIf for bulk operations

// Efficient: Remove multiple items
items.removeIf(item -> item.isExpired());

✗ Avoid frequent removes at beginning

// Bad: O(n) for each removal
while (!queue.isEmpty()) {
process(queue.remove(0)); // Slow!
}
// Better: Use Queue or LinkedList for this

Practice Exercise

Key Takeaways

  • Dynamic sizing: Perfect for unknown or changing collection sizes
  • Random access: O(1) access is ideal for indexed lookups
  • Easy to use: Simple API makes development faster
  • Industry standard: Used in virtually every application
  • Performance aware: Know when to use ArrayList vs other structures