double[] weights = {23.4, 56.7, 90.8};
char[] letters = {'A', 'B', 'C', 'D'};
boolean[] answers = {true, true, false, true};
We can create arrays of object references:
final int SIZE = 3;
String[] names = new String[SIZE];
names[0] = "Bob";
names[1] = "Mary";
names[2] = "Cathy";
We can use an initializer list to create the same array:
String[] names = {"Bob", "Mary", "Cathy"};
We can print each name and its length one per line:
for (int i = 0; i < names.length; i++)
System.out.println(names[i] + " " + names[i].length());
Arrays as Lists
We can use arrays to maintain a "list".
A List is a very important computer science "data structure".
Lists can be:
empty
partially full
full
We can create a list by using:
an array to hold the values in the list
an integer to keep track of how many values are in the list
_______________________
| |
| GROCERY LIST |
| |
|_______________________|
| |
|_______________________|
| |
|_______________________|
| |
|_______________________|
| |
|_______________________|
| |
|_______________________|
| |
|_______________________|
| |
|_______________________|
Grocery List Class
public class GroceryList {
private final int MAX_SIZE = 50;
private int numberOfItems;
private String[] groceries;
public GroceryList() {
groceries = new String[MAX_SIZE];
numberOfItems = 0;
}
public boolean isFull() {
if (numberOfItems == MAX_SIZE)
return true;
else
return false;
}
public boolean isEmpty() {
return numberOfItems == 0;
}
public void addItem(String item) {
if (!isFull()) {
groceries[numberOfItems] = item;
numberOfItems++;
}
}
public int numberOfItems() {
return numberOfItems;
}
public String toString() {
String s = "";
for (int i = 0; i < numberOfItems; i++)
s += groceries[i] + "\n";
return s;
}
public void clear() {
numberOfItems = 0;
}
public static void main(String[] args) {
//Create a new grocery list
GroceryList myList = new GroceryList();
//Add some items
myList.addItem("eggs");
myList.addItem("bacon");
myList.addItem("orange juice");
myList.addItem("coffee");
//Print out the list
System.out.println("\n" + myList);
//Print number of items in list
System.out.println("Number of items: " +
myList.numberOfItems());
//Is list empty OR full?
System.out.println("Empty?: " + myList.isEmpty() +
"\nFull?: " + myList.isFull());
//Clear list
myList.clear();
//Print number of items in list
System.out.println("\nNumber of items: " +
myList.numberOfItems());
//Is list empty OR full?
System.out.println("Empty?: " + myList.isEmpty() +
"\nFull?: " + myList.isFull());
//Add some items
myList.addItem("beer");
myList.addItem("chips");
myList.addItem("salsa");
System.out.println("\n" + myList);
}
}
/* PROGRAM OUTPUT:
csc% java GroceryList
eggs
bacon
orange juice
coffee
Number of items: 4
Empty?: false
Full?: false
Number of items: 0
Empty?: true
Full?: false
beer
chips
salsa
*/