Chapter 6: ArrayLists<E>()

ArrayLists

ArrayLists, type parameter, and for-each loop example

import java.util.ArrayList;

/**
   This bank contains a collection of bank accounts.
*/
public class Bank
{   
   /**
      Constructs a bank with no bank accounts.
   */
   public Bank()
   {
      accounts = new ArrayList();
   }

   /**
      Adds an account to this bank.
      @param a the account to add
   */
   public void addAccount(BankAccount a)
   {
      accounts.add(a);
   }
   
   /**
      Gets the sum of the balances of all accounts in this bank.
      @return the sum of the balances
   */
   public double getTotalBalance()
   {
      double total = 0;
      for (BankAccount a : accounts)
      {
         total = total + a.getBalance();
      }
      return total;
   }

   /**
      Counts the number of bank accounts whose balance is at
      least a given value.
      @param atLeast the balance required to count an account
      @return the number of accounts having least the given balance
   */
   public int count(double atLeast)
   {
      int matches = 0;
      for (BankAccount a : accounts)
      {
         if (a.getBalance() >= atLeast) matches++; // Found a match
      }
      return matches;
   }

   /**
      Finds a bank account with a given number.
      @param accountNumber the number to find
      @return the account with the given number, or null if there
      is no such account
   */
   public BankAccount find(int accountNumber)
   {
      for (BankAccount a : accounts)
      {
         if (a.getAccountNumber() == accountNumber) // Found a match
            return a;
      } 
      return null; // No match in the entire array list
   }

   /**
      Gets the bank account with the largest balance.
      @return the account with the largest balance, or null if the
      bank has no accounts
   */
   public BankAccount getMaximum()
   {
      if (accounts.size() == 0) return null;
      BankAccount largestYet = accounts.get(0);
      for (int i = 1; i < accounts.size(); i++) 
      {
         BankAccount a = accounts.get(i);
         if (a.getBalance() > largestYet.getBalance())
            largestYet = a;
      }
      return largestYet;
   }

   private ArrayList accounts;
}

ArrayLists, type parameter, for-each loop and Iterator another example

/** 
 * mrs.e
 * 12/14/2018
 * 
 * ArrayLists
 * for-each loop
 * Iterator
 * 
 * */

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIterator 
{
   public static void main( String[] args )
   {
      // add elements to an ArrayList
      String[] pets = { "Puppy", "Kitten", "Gerbil", "Bunny", "Ferret" };
      ArrayList< String > aList = new ArrayList< String >();      

      for ( String pet : pets )
         aList.add( pet ); // for each loop - don't change the ArrayList   

      // add elements in removePets array to removeList
      String[] removePets = { "Gerbil", "Bunny" };
      ArrayList< String > removeList = new ArrayList< String >();

      for ( String pet : removePets )
         removeList.add( pet ); 

      // print items of the list
      System.out.println( "ArrayList: " );

      for ( int count = 0; count < aList.size(); count++ )
         System.out.printf( "%s ", aList.get( count ) );

      // remove from list the pets contained in removeList
      removePets( aList, removeList );

      // print itmes of the list 
      System.out.println( "\n\nArrayList after calling removePets: " );

      for ( String pet : aList )
         System.out.printf( "%s ", pet );
   } // end main

   // remove pets in collection2 found in collection1
   private static void removePets( ArrayList< String > collection1, 
      ArrayList< String > collection2 )
   {
      // get iterator
      Iterator< String > iterator = collection1.iterator(); 

      // loop while collection has items
      while ( iterator.hasNext() )         
      {
         if ( collection2.contains( iterator.next() ) )
            iterator.remove(); // remove current pet
      } // end while
   } // end method removePets
} // end class ArrayListIterator

indexOf and lastIndexOf example from http://www.dotnetperls.com/arraylist-java

import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

    ArrayList list = new ArrayList<>();
    list.add(101);
    list.add(100);
    list.add(99);
    list.add(100);
    list.add(99);

    // Search for values.
    int index = list.indexOf(100);
    int lastIndex = list.lastIndexOf(100);
    int notFound = list.indexOf(200);

    // Display results.
    System.out.println(index);     // 1
    System.out.println(lastIndex); // 3
    System.out.println(notFound);  // -1
    }
}

Output

1
3
-1

§ § § § § §

More advanced topics in this link. (Optional)

ListIterator, indexOf, Iterator, List Interface
Screen Shot 2014-12-15 at 9.05.33 PM

[collapse]

Screen Shot 2014-12-11 at 9.19.49 PM

Screen Shot 2014-12-11 at 9.26.39 PM

ArrayList<E>()

Constructs an empty list with an initial capacity of ten.

Screen Shot 2014-12-11 at 9.30.09 PM

boolean add(E obj)
Appends the specified element to the end of this list.

void add(int index, E obj)
Inserts the specified element at the specified position in this list.

E get(int index)
Returns the element at the specified position in this list.

int indexOf(Object obj)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

boolean isEmpty()
Returns true if this list contains no elements.

int size()
Returns the number of elements in this list.

ListIterator<E> listIterator()

Returns a list iterator over the elements in this list (in proper sequence).

E remove(int index)
Removes the element at the specified position in this list.

boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.

//********************************************************************
//  DestinysChild.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a ArrayList object.
//********************************************************************

import java.util.ArrayList;

public class DestinysChild
{
   //-----------------------------------------------------------------
   //  Stores and modifies a list of band members.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      ArrayList band = new ArrayList();

      band.add ("Michelle");
      band.add ("Kelly");
      band.add ("Beyonce");
      band.add ("Farrah");

      System.out.println (band);

      int location = band.indexOf ("Farrah");
      band.remove (location);

      System.out.println (band);
      System.out.println ("At index 1: " + band.get(1));

      System.out.println (band);
      System.out.println ("Size of the band: " + band.size());
   }
}


[Michelle, Kelly, Beyonce, Farrah]
[Michelle, Kelly, Beyonce]
At index 1: Kelly
[Michelle, Kelly, Beyonce]
Size of the band: 3

Two ways to iterate through the elements of a collection in java:

  1. By Iterator interface.
  2. By for-each loop.
//********************************************************************
//  Recipe.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the use of a ListIterator to iterate through the
//  elements of an ArrayList.
//********************************************************************

import java.util.ArrayList;
import java.util.ListIterator;

public class Recipe
{
   //-----------------------------------------------------------------
   //  Stores and then prints a list of ingredients for a recipe.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      ArrayList ingredients = new ArrayList();

      ingredients.add ("flour");
      ingredients.add ("sugar");
      ingredients.add ("cocoa");
      ingredients.add ("oil");
      ingredients.add ("butter");
      ingredients.add ("eggs");
      ingredients.add ("baking soda");

      System.out.println ("To make a chocolate cake, use the following " +
         ingredients.size() + " ingredients:");

      // traversing ArrayList by Iterator
      ListIterator iterator = ingredients.listIterator(); 
      while (iterator.hasNext())
         System.out.println(iterator.next());

      // traversing ArrayList using the "for-each" loop
       for(String obj:ingredients)  
          System.out.println(obj);  

   }
}

To make a chocolate cake, use the following 7 ingredients:
flour
sugar
cocoa
oil
butter
eggs
baking soda

Classwork/Homework:
1. Create a class DataSet of BankAccounts. The constructor creates an ArrayList of BankAccount(s). Write the test class to add, delete and print (use the for-each loop) bank accounts. Your driver should have at least 3 BankAccount objects. Make any changes necessary to have the DataSet ADT implemented with an ArrayList. Also, change the comments to fit the modifications to the it.

DataSet with ArrayList

/**
   Computes the average of a set of data values.
*/
public class DataSet
{
   /**
      Constructs an empty data set with no BankAccount objects.
   */
   public DataSet()
   {
      sum = 0;
      count = 0; // Warning: Is "count" necessary?
      maximum = 0; // Warning: this should not be a numeric type!!
      // create an object of the ArrayList dataSet
   }

   /**
      Adds a BankAccount object to the data set
      @param x a BankAccount object
   */
   public void add(BankAccount bank)
   {
      // add object to ArrayList
      sum = sum + bank.getBalance();
      if (count == 0 || maximum.getBalance() < x.getBalance()) maximum = x;
      count++;
   }

   /**
      Gets the average of the added BankAccount balances.
      @return the average or 0 if no data has been added
   */
   public double getAverage()
   {
      if (count == 0) return 0;
      else return sum / count;  // Warning
   }

   /**
      Gets the largest of the added data. // changes must be made here
      @return the maximum or 0 if no data has been added
   */
   public BankAccount getMaximum()
   {
      return maximum;
   }

   /**
      Prints the balance for each element of the added data in the ArrayList.// Warning
      @return the average or 0 if no data has been added
   */
   public void printDataSet()
   {
     // implement the code to print the elements of the ArrayList datSet. Add more specific comments
     // use the for-each loop
   }

   private double sum;
   private BankAccount maximum;
   private int count;
   private ArrayList dataSet;
}

[collapse]
  1. Create a class Purse (see below) that contains an ArrayList of Coin(s). Write the test class to add, delete, and print coins. Make any changes necessary to have the Purse class implemented with an ArrayList. Also, change the comments to fit the modifications to the ADT.
/**
   A coin with a monetary value.
*/
public class Coin
{
   /**
      Constructs a coin.
      @param aValue the monetary value of the coin.
      @param aName the name of the coin
   */
   public Coin(double aValue, String aName) 
   { 
      value = aValue; 
      name = aName;
   }

   /**
      Gets the coin value.
      @return the value
   */
   public double getValue() 
   {
      return value;
   }

   /**
      Gets the coin name.
      @return the name
   */
   public String getName() 
   {
      return name;
   }

   public boolean equals(Object otherObject)
   {  
      Coin other = (Coin)otherObject;
      return name.equals(other.name) 
         && value == other.value; 
   }

   private double value;
   private String name;
}

Modify the Purse class to be implemented with ArrayList<Coin> and to use a for-each loop.
Implement the following methods in the Purse class:

   /**
      Counts the number of coins in the purse
      @return the number of coins
   */
   public int count()
   {
     
   }

   /**
      Tests if the purse has a coin that matches
      a given coin.
      @param aCoin the coin to match
      @return true if there is a coin equal to aCoin
   */
   public boolean find(Coin aCoin)
   {

   }

   /**
      Counts the number of coins in the purse that match
      a given coin.
      @param aCoin the coin to match
      @return the number of coins equal to aCoin
   */
   public int count(Coin aCoin)
   {

   }

   /**
      Finds the coin with the largest value. 
      (Precondition: The purse is not empty)
      @return a coin with maximum value in this purse
   */
   pulic Coin getMaximum()
   {

   }

NOTE: Use the “for-each” loop in the implementation.