Extra Data Types
Beyond the basic data types (int, double, boolean, String), Java has specialized types for specific situations.
Enums
An enum represents a fixed set of named constants:
public enum ClawState {
OPEN,
CLOSED,
CLOSED_PARTIAL,
INTAKE_CLOSE
}
Using Enums
public class Claw {
public enum State {
CLOSED, OPEN, CLOSED_PARTIAL, INTAKE_CLOSE, CLOSED_WALL
}
public static State state;
public void setState(State newState) {
state = newState;
switch(state) {
case OPEN:
claw.setPosition(OUTTAKE_CLAW_OPEN);
break;
case CLOSED:
claw.setPosition(OUTTAKE_CLAW_CLOSED);
break;
case CLOSED_PARTIAL:
claw.setPosition(OUTTAKE_CLAW_CLOSED_PARTIAL);
break;
}
}
}
// Usage
robotClaw.setState(Claw.State.OPEN);
Arrays
Arrays store multiple values of the same type:
// Declaration and initialization
double[] motorPowers = new double[4];
String[] teamNames = {"Team A", "Team B", "Team C"};
// Access by index (starts at 0)
motorPowers[0] = 0.5;
String firstTeam = teamNames[0];
// Get length
int arraySize = motorPowers.length;
ArrayLists
ArrayLists are resizable arrays that can grow and shrink:
import java.util.ArrayList;
ArrayList<String> teamMembers = new ArrayList<>();
// Add elements
teamMembers.add("Alice");
teamMembers.add("Bob");
// Access elements
String member = teamMembers.get(0);
// Remove elements
teamMembers.remove("Bob");
// Get size
int size = teamMembers.size();
Generic Types
ArrayLists use generic types to specify what they contain:
ArrayList<Integer> scores = new ArrayList<>();
ArrayList<Double> distances = new ArrayList<>();
ArrayList<Boolean> states = new ArrayList<>();
Quick Reference
| Type | What It Stores | Example |
|---|---|---|
enum | Fixed set of named constants | ClawState.OPEN |
array[] | Fixed-size list of same type | int[] numbers = {1,2,3} |
ArrayList | Resizable list of same type | ArrayList<String> names |