5064 comments
1960 subscribers
4800 on Twitter
Subscribe! Feed reader E-mail

Sample ArrayList code

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

Short URL: http://sachachua.com/blog/p/1753

Comment, share a thought, ask a question...

Please comment as you, not your organization.





 

On This Day...

  • 2012: Experience report: Opening the RBC Small Business eAccount — Having a business bank account is good for separating business and personal expenses. Reconciling your books is easier when you [...]
  • 2011: Posted revised “Remote Presentations That Rock” presentation — Next week, I’m giving Remote Presentations That Rock in person at IBM 3600 Steeles Avenue on Monday. I decided to [...]
  • 2010: Winter — This winter feels a lot milder and happier than the others I’ve been through. A large part of that comes [...]
  • 2009: On the other side of the (virtual) desk — If I’m going to take over the world, I need to learn how to delegate. ;) It’s a simple matter of [...]
  • 2008: Weekly review – Week ending February 24
  • 2006: Had a blast! — I went up to IBM Cambridge today, and it was absolutely fantastic. I’m not sure if I can talk about what [...]
  • 2004: Apache James — JM Ibanez suggested looking at Apache James and writing a mailet. Nifty idea, if I can get my mind around it! (I [...]
  • 2004: SocialNetworkBot — This is where all the magic happens. Starting up the app for every arriving message is probably a bad idea. Better [...]
  • 2004: SocialNetworkBot — This is where all the magic happens. Starting up the app for every arriving message is probably a bad idea. Better [...]
  • 2004: Social network analysis — http://www.jibble.org/piespy/ I want to run something like this on the PLUG mailing lists. I can reuse their spring model and then build [...]
  • 2004: Common networking errors — Due 2004.02.23 11:59:59 PM: Source code and detailed notes on - changes made - problems encountered - solutions tried/found - outstanding problems - plans for [...]
  • 2004: Sample ArrayList code — Here’s sample code for ArrayLists, which is a Java class that can store any kind of object in an array that [...]
  • 2004: Nvu, a WYSIWYG HTML editor for Linux — http://www.nvu.com/index.html
  • 2004: planner.el broken up into lots of little files — It should compile cleanly under Emacs 21.3 (CVS). I’m still trying to figure out how to install the fsf-compat package under [...]
  • 2004: Social networking diagram — Should be fun to run this on a mailing list, using the References: tag… - http://www.jibble.org/piespy - http://www.daimi.au.dk/~terryp/pics/emacs-current.png
  • 2003: done with highlighting my readings — Whew!
  • 2003: emacspeak and IRC — linux — I am beginning to realize just how wonderful speech is. I’ve added dtk-speak to erc-insert-pre-hook, and I can listen to #linuxhelp [...]
  • 2003: linux printing site — http://www.linuxprinting.com, if I forget