Data Bundles

Learn how to group and manage data in Java. Java requires you to be very explicit when you prepare a bundle.


1. A line-up bundle: List

This is the most common form. We usually use ArrayList.

import java.util.ArrayList;

ArrayList<String> shoppingList = new ArrayList<>();

// Add
shoppingList.add("apple");
shoppingList.add("banana");

// Update
shoppingList.set(0, "strawberry"); // change index 0

// Remove
shoppingList.remove(1); // remove index 1

System.out.println(shoppingList);

Translation:

Create a new ArrayList of strings and name it shoppingList;

Add "apple" to shoppingList;
Add "banana" to shoppingList;
Change box 0 to "strawberry";
Remove box 1;

Print shoppingList;

2. A labeled bundle: Map

A dictionary-like structure where you look up values by key. We usually use HashMap.

import java.util.HashMap;

HashMap<String, String> myInfo = new HashMap<>();

// Add & update
myInfo.put("name", "Alex");
myInfo.put("age", "20");

// Remove
myInfo.remove("age");

System.out.println(myInfo.get("name")); // get "Alex"

Translation:

Create a new HashMap where both keys and values are strings, and name it myInfo;

Put "Alex" under the "name" tag;
Remove the "age" tag;

Java bundles can look complicated at first (new ArrayList<>(), etc.), but once you remember them, they are very powerful.