Sample ArrayList code

| -Uncategorized

Here’s sample code for ArrayLists, which is a Java class that can
store any kind of object in an array that automatically grows.

Note: ArrayLists store objects. Generic objects. You’ll probably
need to convert (“cast”) them to another type before you can use them.
See example below.

Note: Only objects. You can’t store doubles, ints or booleans unless
they’re wrapped in another object. You can’t say list.add(5), but you
can wrap it in an Integer object and say list.add(new Integer(5));.
Then you can say Integer x = (Integer) list.get(0);
System.out.println(x.intValue());

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
// NEW: You need this for ArrayList
import java.util.*;

public class OrderApplet extends Applet implements ActionListener
{
    private TextField nameField;
    private TextField orderField;
    private TextField valueField;
    private TextField indexField;
    private TextField nameFilterField;
    private Button addButton;
    private Button removeButton;
    private Button showAllButton;
    private Button showOnlyButton;
    private TextArea outputArea;

    // NEW: Declare the array list
    private ArrayList orderList;

    public void init()
    {
        // NEW: Create the array list
        orderList = new ArrayList();

        Label nameLabel = new Label("Name: ");
        add(nameLabel);
        nameField = new TextField(10);
        add(nameField);

        Label orderLabel = new Label("Order: ");
        add(orderLabel);
        orderField = new TextField(10);
        add(orderField);

        Label valueLabel = new Label("Value:");
        add(valueLabel);
        valueField = new TextField(5);
        add(valueField);

        addButton = new Button("Add order");
        addButton.addActionListener(this);
        add(addButton);

        Label indexLabel = new Label("Index:");
        add(indexLabel);
        indexField = new TextField(5);
        add(indexField);
        removeButton = new Button("Remove order at index");
        removeButton.addActionListener(this);
        add(removeButton);

        showAllButton = new Button("Show all orders");
        showAllButton.addActionListener(this);
        add(showAllButton);

        nameFilterField = new TextField(10);
        add(nameFilterField);
        showOnlyButton = new Button("Show selected orders");
        showOnlyButton.addActionListener(this);
        add(showOnlyButton);

        outputArea = new TextArea(20, 50);
        add(outputArea);

    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == addButton)
        {
            // Get the values from the text fields
            String name = nameField.getText();
            String order = orderField.getText();
            double value = Double.parseDouble(valueField.getText());
            // Create an Order object for these three items
            Order o = new Order(name, order, value);
            // Add the value to the list of orders
            // NEW: Add o to the list.
            orderList.add(o);
            showAllOrders();
        }
        else if (e.getSource() == removeButton)
        {
            int index = Integer.parseInt(indexField.getText());
            // NEW: Remove the object at the specified position.
            orderList.remove(index);
            showAllOrders();
        }
        else if (e.getSource() == showAllButton)
        {
            showAllOrders();
        }
        else if (e.getSource() == showOnlyButton)
        {
            showOrders(nameFilterField.getText());
        }
    }

    // TODO: Add a total
    public void showAllOrders()
    {
        // FIXME: Declare a temporary sum variable and set it to 0.0.

        // Update the order display no matter what button is clicked.
        outputArea.setText("");
        // NEW: Getting the size with the size() method.
        for (int i = 0; i < orderList.size(); i++)
        {
            // An ArrayList stores generic Objects.
            // All objects in Java are of the Object class.
            // If we want to use special methods of the Order
            // class, we have to tell Java it's an Order object.
            // (Order) before orderList.get(i) converts the
            // result into an Order object.

            // NEW: Casting (converting one object to another), .get(index)
            Order order = (Order) orderList.get(i);
            // What happens if you remove (Order) from the line above?

            outputArea.append("[" + i + "]: "  // index
                              + order.getName() + ": "
                              + order.getOrder() + ": "
                              + order.getValue() + "\n");
            // FIXME: Add the order value to the sum
        }
        // FIXME: Display the sum
    }

    // TODO: Add a total
    public void showOrders(String name)
    {
        // FIXME: Declare a temporary sum variable and set it to 0.0.

        // Show only the orders by a certain person
        outputArea.setText("");
        for (int i = 0; i < orderList.size(); i++)
        {
            Order order = (Order) orderList.get(i);
            // What happens if you remove (Order) from the line above?
            if (order.getName().equals(name))
            {
                outputArea.append("[" + i + "]: "  // index
                                  + order.getName() + ": "
                                  + order.getOrder() + ": "
                                  + order.getValue() + "\n");
                // FIXME: Add the order value to the sum
            }
        }
        // FIXME: Display the sum
    }
}

class Order
{
    private String name;
    private String order;
    private double value;

    public Order(String name,
                 String order,
                 double value)
    {
        // "this.name" refers to the name attribute,
        // but "name" by itself refers to the parameter.
        this.name = name;
        this.order = order;
        this.value = value;
    }

    public String getName()
    {
        // The "this." in this.name here is optional, but
        // we use it anyway: it's good practice
        return this.name;
    }

    public String getOrder()
    {
        return this.order;
    }

    public double getValue()
    {
        return this.value;
    }

}

../../notebook/school/current/cs21a/OrderApplet.java

You can comment with Disqus or you can e-mail me at sacha@sachachua.com.