Monday, April 16, 2012

ArrayList Sample

These classes show a Sale class that contains an ArrayList of items. Item is a separate class that acts as a container for a set of fields.

Here is the code

Here is Item.java



public class Item {
 private String itemNumber;
 private String itemName;
 private double ItemPrice;
 
 public String getItemNumber() {
  return itemNumber;
 }
 public void setItemNumber(String itemNumber) {
  this.itemNumber = itemNumber;
 }
 String getItemName() {
  return itemName;
 }
 void setItemName(String itemName) {
  this.itemName = itemName;
 }
 double getItemPrice() {
  return ItemPrice;
 }
 void setItemPrice(double itemPrice) {
  ItemPrice = itemPrice;
 }
}


Sale.java

import java.util.*;
public class Sale {

 String saleNumber;
 String saleDate;
 ArrayList<Item> items;
 
 public Sale(String saleNumber, String saleDate){
  this.saleNumber=saleNumber;
  this.saleDate=saleDate;
  items=new ArrayList<Item>();
 }
 
 public void addItem(Item i){
  items.add(i);
 }
 
 public ArrayList<Item> getItems(){
  return items;
 }
 
 public double calculateTotalSale(){
  double total=0;
  for(Item i : items){
   total+=i.getItemPrice();
  }
  return total;
 }
}


Main.java

import java.util.*;

public class Main {

 /**
  * @param args
  */
 
 Sale s;
 
 public static void main(String[] args) {
  
  Main m = new Main();
  m.CreateSale();
  m.ReadSale();
 
  
 }
 
 private void CreateSale()
 {
  s = new Sale("2221", "4/16/2012");
  Item i = new Item();
  i.setItemName("Apple");
  i.setItemNumber("1");
  i.setItemPrice(1000000.00);
  s.addItem(i);
  
  Item i2 = new Item();
  i2.setItemName("IBM");
  i2.setItemNumber("2");
  i2.setItemPrice(100000.00);
  s.addItem(i2);
 }
 
 private void ReadSale(){
  ArrayList<Item>items=s.getItems(); 
  for(Item item : items ){
   System.out.println(item.getItemName());
   System.out.println(item.getItemPrice());
  }
  
  System.out.println(s.calculateTotalSale());
 }

}

No comments:

Post a Comment