Arrays can be used as fields in classes. This fits well with the object-based design in many Java programs. Here, we place an apartmentIds array in the Building class.
class Building {
int[] apartmentIds = new int[10];
public void addResidentAt(int id) {
// Add to the array at this index.
apartmentIds[id]++;
}
public void removeResidentAt(int id) {
// Subtract from element value.
apartmentIds[id]--;
}
public int getOccupancyAt(int id) {
// Return element value.
return apartmentIds[id];
}
}
public class Program {
public static void main(String[] args) {
// Create a Building.
// ... Some residents move in and one leaves.
Building b = new Building();
b.addResidentAt(5);
b.addResidentAt(3);
b.addResidentAt(9);
b.removeResidentAt(5);
// Display occupancy of apartments.
for (int i = 0; i < 10; i++) {
System.out.println(Integer.toString(i) +
": " + b.getOccupancyAt(i));
}
}
}
0: 0
1: 0
2: 0
3: 1
4: 0
5: 0
6: 0
7: 0
8: 0
9: 1