Sunteți pe pagina 1din 32

MELJUN

CORTES,MBA,MPA,BSCS,ACS
class Rectangle
{
private double width = 10.0;
private double length = 15.0;

public Rectangle()
{
// do nothing, defaults are fine
}

public Rectangle(double width, double length)


{
this.width = width; OUTPUT:
this.length = length;
}

// create square given just one side


public Rectangle(double side)
{
length = width = side;
}

public double getWidth() { return width; }


public double getLength() { return length; }
public double getPerim() { return 2 * width + 2 * length; }
public double getArea() { return width * length; }

class RectangleTester
{

// the tester program


public static void main(String[] args)
{
Rectangle r1 = new Rectangle();
System.out.println("r1: " + r1.getWidth() + " x " + r1.getLength() +
" Perim: " + r1.getPerim() + " Area: " + r1.getArea() );

Rectangle r2 = new Rectangle(20.0, 40.0);


System.out.println("r2: " + r2.getWidth() + " x " + r2.getLength() +
" Perim: " + r2.getPerim() + " Area: " + r2.getArea());

Rectangle r3 = new Rectangle(10.0); // pass in one side


System.out.println("r3: " + r3.getWidth() + " x " + r3.getLength() +
" Perim: " + r3.getPerim() + " Area: " + r3.getArea());

}
MELJUN
CORTES,MBA,MPA,BSCS,ACS

import java.text.NumberFormat;

class Employee
{
private String name;
private double salary;

OUTPUT:
// constructor initializes the members
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}

// overloaded - takes one double


public double getBonus(double percent)
{
return salary * percent;
}

// overloaded - takes two double


public double getBonus(double percent, double additional)
{
return salary * percent + additional;
}

// overloaded - takes three doubles


public double getBonus(
double percent,
double additional,
double max)
{
double bonus = salary * percent + additional;
return bonus <= max ? bonus : max;
}

// overloaded - takes four doubles


public double getBonus(
double percent,
double additional,
double max,
double min)
{
double bonus = salary * percent + additional;

// if in range, return the bonus


if ( (bonus < max) && (bonus > min) )
{
return bonus;
}
MELJU
else // out of range, return max or min
{
return bonus > max ? max : min;
}
}
}

class EmployeeBonusOverloadedMethod
{

// the tester program


public static void main(String[] args)
{
Employee emp1 = new Employee("John", 50000);
double bonus = emp1.getBonus(.5);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String bonusString = formatter.format(bonus);
System.out.println("John's bonus:\t" + bonusString);

Employee emp2 = new Employee("Paul", 75000);


bonus = emp2.getBonus(.25, 10000);
bonusString = formatter.format(bonus);
System.out.println("Paul's bonus:\t" + bonusString);

Employee emp3 = new Employee("George", 100000);


bonus = emp3.getBonus(.50, 25000, 60000);
bonusString = formatter.format(bonus);
System.out.println("George's bonus:\t" + bonusString);

Employee emp4 = new Employee("Ringo", 20000);


bonus = emp4.getBonus(.20, 5000, 60000, 10000);
bonusString = formatter.format(bonus);
System.out.println("Ringo's bonus:\t" + bonusString);

}
}

OUTPUT:
MELJU
class Employee
{
private String name;
private double salary;

// constructor initializes the members


public Employee(String name, double salary)
{
this.name = name; OUTPUT:
this.salary = salary;
}

public double getBonus(double percent)


{
return salary * percent;
}
}

class EmployeeBonus
{

// the tester program


public static void main(String[] args)
{
Employee emp = new Employee("Joe", 50000);
double bonus = emp.getBonus(.5);

System.out.println("Joe's bonus: $" + bonus);


}
}

OUTPUT:
MELJU
class SimpleArray
{
public static void main(String[] args)
{
SimpleArray s = new SimpleArray();
s.run();
} OUTPUT:

public void run()


{
// an array of 10 integers
int[] array1 = new int[10];

// directly fill the array


array1[0] = 2;
array1[1] = 4;
array1[2] = 6;
array1[3] = 8;
array1[4] = 10;
array1[5] = 12;
array1[6] = 14;
array1[7] = 16;
array1[8] = 18;
array1[9] = 20;

// display the contents


System.out.println("First time:");
for ( int i = 0; i < 10; i++ )
{
System.out.println(i + ": " + array1[i]);
}

// reuse the array reference


array1 = new int[10];

// fill the array in a for loop


for ( int i = 0; i < 10; i++ )
{
array1[i] = i * 3;
}

// display the contents


System.out.println("\nSecond time:");
for ( int i = 0; i < 10; i++ )
{
System.out.println(i + ": " + array1 [i]);
} // end for
} // end run
} // end class
MELJU
class SimpleArrayInitialization
{
public static void main(String[] args)
{
SimpleArrayInitialization s = new SimpleArrayInitialization();
s.run();
}

public void run()


{
// an array of 10 integers
int[] array1 = {2,4,6,8,10,12,14,16,18,20};

// display the contents


System.out.println("array1:");
for ( int i = 0; i < 10; i++ )
{
System.out.println(i + ": " + array1[i]);
}

} // end run
} // end class

OUTPUT:

class SumOfDice
{
int[] diceValues = new int[13];

public static void main(String[] args)


{
SumOfDice d = new SumOfDice();
d.run();
}
private void run()

MELJU
{
System.out.print("Rolling...");

// roll the die one million times


for ( int i = 0; i < 1000000; i++ ) OUTPUT:
{
// print a dot every 100,000 times
if ( i % 100000 == 0 )
{
System.out.print(".");
}

int die1 = rollDie();


int die2 = rollDie();

diceValues[die1 + die2]++;
}

display();
}

private void display()


{
System.out.print("\n\n");

// tick through the array


for ( int i = 2; i <= 12; i++ )
{
System.out.println(i + ":\t" + diceValues[i]);
}
}

private int rollDie()


{
// 0 <= randomNumber < 1
double randomNumber = java.lang.Math.random();

// 0 <= randomNumber < 6


randomNumber *= 6;

// cast to an int (lop off the fraction)


int choice = (int) randomNumber;

choice++; // change to 1-6

return (choice);
}
}
// place at top of file

MELJU
import java.text.NumberFormat;

class SumOfDiceHistogram
{
int[] diceValues = new int[13];

public static void main(String[] args)


{
SumOfDiceHistogram d = new SumOfDiceHistogram();
d.run();
}

private void run()


{
System.out.print("Rolling...");

// roll the die one million times


for ( int i = 0; i < 1000000; i++ )
{
// print a dot every 100,000 times
if ( i % 100000 == 0 )
{
System.out.print("."); OUTPUT:
}

int die1 = rollDie();


int die2 = rollDie();

diceValues[die1 + die2]++;
}

display();
}

public void display()


{
System.out.print("\n\n");

// tick through the array


for ( int i = 2; i <= 12; i++ )
{
int scaledValue = diceValues[i] / 5000;

System.out.print(i + ":\t");
for ( int j = 0; j < scaledValue; j++ )
{
System.out.print("*");
}
}
// display the total found

MELJU
NumberFormat formatter = NumberFormat.getNumberInstance();
String totalFound = formatter.format(diceValues[i]);
System.out.println(" [" + totalFound + "]");

private int rollDie()


{
// 0 <= randomNumber < 1
double randomNumber = java.lang.Math.random();

// 0 <= randomNumber < 6


randomNumber *= 6;

// cast to an int (lop off the fraction)


int choice = (int) randomNumber;

choice++; // change to 1-6

return (choice);
}
}

OUTPUT:
MELJU
import java.text.NumberFormat;

// Histogram - a bar chart representing a


// frequency distribution
class Histogram
{
// allows you to track numbers from low to high
// rather than from zero offset
private int lowOffset;
private int highOffset;

// hold the results in an array


private int[] theArray;

// constructor takes low and high, creates


// array and stores low and high values
public Histogram(int low, int high)
{
lowOffset = low; // arrays count from zero
highOffset = high;
theArray = new int[high - low + 1]; // size the array
}

// given an index, increment the value at the


// appropriate offset
public void increment(int index)
{
int adjustedIndex = index - lowOffset;
theArray[adjustedIndex]++;
}

// scale the values by division


// if scale = 1,000 show every 1,000th as *
public void display(int scale)
{
System.out.print("\n\n");

// tick through the array


for ( int i = 0; i < highOffset - lowOffset + 1; i++ )
{
int scaledValue = theArray[i] / scale;

int adjustedOffset = i + lowOffset;


System.out.print(adjustedOffset + ":\t");
for ( int j = 0; j < scaledValue; j++ )
{ OUTPUT:
System.out.print("*");
}
MELJU
// display the total found
NumberFormat formatter = NumberFormat.getNumberInstance();
String totalFound = formatter.format(theArray[i]);
System.out.println(" [" + totalFound + "]");
}
}
}

class HistogramTwoDie
{

public static void main(String[] args)


{
HistogramTwoDie h = new HistogramTwoDie();
h.run();
}

public void run()


{
// create a histogram to hold
// the values of two dice
Histogram histogram = new Histogram(2,12);
System.out.print("Rolling...");

// roll the dice one million times


for ( int i = 0; i < 1000000; i++ )
{
// print a dot every 100,000 times
if ( i % 100000 == 0 )
{
System.out.print(".");
}
int firstDie = rollDie();
int secondDie = rollDie();
histogram.increment(firstDie + secondDie);
}
// print with one * = 5,000
histogram.display(5000);
}

private int rollDie()


{
// 0 <= randomNumber < 1
double randomNumber = java.lang.Math.random(); OUTPUT:
// 0 <= randomNumber < 6
randomNumber *= 6;

// cast to an int (lop off the fraction)


int choice = (int) randomNumber;

// 1 <= choice <= 6


choice++;
return (choice);
}
}
MELJU
class DoubleInts
{
public static void main(String[] args) OUTPUT:
{
DoubleInts d = new DoubleInts();
d.run();
}

// Double an integer.
// Beware of pass by value!
private void doubler(int theInt)
{
System.out.println("doubler was: " + theInt);
theInt *= 2;
System.out.println("doubler now: " + theInt);
}

public void run()


{
int x = 15;
System.out.println("run before doubler: " + x);
doubler(x);
System.out.println("run after doubler: " + x );

} // end run
} // end class

class Employee
{
public int age; OUTPUT:
public String name;

public Employee(String name, int age)


{
this.name = name;
this.age = age;
}

public String toString()


{
return (name + "(" + age + ")");
}
}

class ByReference
{
private void modify(Employee theEmployee)
{
System.out.println("modify received: " + theEmployee);
theEmployee.age /= 2; //cut age in half
theEmployee.name = "New Name";
System.out.println("after modification: " + theEmployee);
}
MELJU
public void run()
{
Employee joe = new Employee("Joe", 45);
System.out.println("run before modifcation: " + joe);
modify(joe);
System.out.println("run after modification: " + joe);
}

public static void main(String[] args)


{
ByReference b = new ByReference();
b.run();
}
}

class DoubleArray
{
public static void main(String[] args)
{
DoubleArray d = new DoubleArray();
d.run();
}

private void doubler(int[] theArray)


{
System.out.println("\ndoubler received this array:");
for ( int i = 0; i < theArray.length; i++ )
{
System.out.print(theArray[i] + " ");
}

for ( int i = 0; i < theArray.length; i++ )


{
theArray[i] *= 2;
}

System.out.println("\ndoubler modified the array to: ");


for ( int i = 0; i < theArray.length; i++ )
{
System.out.print(theArray[i] + " ");
} OUTPUT:
}
MELJU
public void run()
{
int[] intArray = {1,3,5,7,9,11,13,15};

System.out.println("\nthe array in run:");


for ( int i = 0; i < intArray.length; i++ )
{
System.out.print(intArray[i] + " ");
}

doubler(intArray);

System.out.println("\nthe array back in run:");


for ( int i = 0; i < intArray.length; i++ )
{
System.out.print(intArray[i] + " ");
}
System.out.println();
} // end run
} // end class

class DoubleArray2
{
public static void main(String[] args)
{
DoubleArray2 d = new DoubleArray2();
d.run();
}

// Double an integer.
// Beware of pass by value!
private void doubleAnInt(int theInt)
{
System.out.println("doubleAnInt received: " + theInt);
theInt *= 2;
System.out.println("doubleAnInt modified to: " + theInt);
} OUTPUT:

public void run()


{
int[] intArray = {1,3,5,7,9,11,13,15};

// extract a single member from the array and


// pass that to the doubleAnInt method

for ( int i = 0; i < intArray.length; i++ )


{
doubleAnInt(intArray[i]);
}
MELJU
System.out.println(
"\nthe array back in run after calling doubleAnInt");
for ( int i = 0; i < intArray.length; i++ )
{
System.out.print(intArray[i] + " ");
}
System.out.println("");
} // end run
} // end class

OUTPUT:

import java.text.NumberFormat;

class DieArray2D
{
// constant for how many times to
// iterate over the experiment
static final int ITERATIONS = 10;

// two-dimensional array to hold rolls of the dice


// rows = each experiment
// columns = each total (e.g., 2-12)
int[][] diceValues = new int[ITERATIONS][13];

public static void main(String[] args)


{
DieArray2D d = new DieArray2D();
d.run();
}
MELJU
public void run()
{
System.out.print("Rolling...");

// outer loop - once for each iteration


for ( int iteration = 0; iteration < ITERATIONS; iteration++ )
{
System.out.print("\nIteration: " + iteration + "...");

// roll the die one million times


for ( int i = 0; i < 1000000; i++ )
{
// print a dot every 100,000 times
if ( i % 100000 == 0 )
{
System.out.print(".");
}

int firstRoll = rollDie();


int secondRoll = rollDie();

diceValues[iteration][firstRoll + secondRoll]++;
}
}

display();
}
public void display()
{
// outer loop - once for each iteration
for ( int iteration = 0; iteration < ITERATIONS; iteration++ )
{
System.out.print("\n");

// tick through the array


// and display the totals found
for ( int i = 2; i <= 12; i++ )
{
System.out.print(diceValues[iteration][i] + " "); OUTPUT:
}
}
System.out.print("\n");
}
private int rollDie()
{
// 0 <= randomNumber < 1
double randomNumber = java.lang.Math.random();

// 0 <= randomNumber < 6


randomNumber *= 6;

// cast to an int (lop off the fraction)


int choice = (int) randomNumber;

choice++; // change to 1-6

return (choice);
}
}

**************************************************************************************************************
MELJU
OUTPUT:

import java.text.NumberFormat;

class DieArray2DWithTotals
{
static final int ITERATIONS = 10;
static final int LOW = 0;
static final int HIGH = 1;

int[][] diceValues = new int[ITERATIONS][13];


int[][] totals = new int[13][2];

public static void main(String[] args)


{
DieArray2DWithTotals d = new DieArray2DWithTotals();
d.run();
}

public void run()


{
System.out.print("Rolling...");

// outer loop - once for each iteration


for ( int iteration = 0; iteration < ITERATIONS; iteration++ )
{
System.out.print("\nIteration: " + iteration + "...");
MELJU
// roll the die one million times
for ( int i = 0; i < 1000000; i++ )
{
// print a dot every 100,000 times
if ( i % 100000 == 0 )
{
System.out.print(".");
}

int firstRoll = rollDie();


int secondRoll = rollDie();

diceValues[iteration][firstRoll + secondRoll]++;
}
}

display();

public void display()


{

// outer loop - once for each iteration


for (int iteration = 0; iteration < ITERATIONS; iteration++)
{
System.out.print("\n");
// tick through the array
for ( int i = 2; i <= 12; i++ )
{
System.out.print(diceValues[iteration][i] + " ");

int currentHighest = totals[i][HIGH];


int currentValue = diceValues[iteration][i];

if ( currentHighest < currentValue )


{
totals[i][HIGH] = currentValue;
}

/*
totals[i][HIGH] =
(totals[i][HIGH] < diceValues[iteration][i]) ?
diceValues[iteration][i] :
totals[i][HIGH];
*/

int currentLowest = totals[i][LOW] ;


currentValue = diceValues[iteration][i];

if ( currentLowest > currentValue || currentLowest == 0 )


{
totals[i][LOW] = currentValue;
}
/*
totals[i][LOW] =
(totals[i][LOW] > diceValues[iteration][i] ||
totals[i][LOW] == 0) ?
diceValues[iteration][i] :
MELJU
totals[i][LOW];
OUTPUT:
*/
}
}
System.out.print("\n\n");

for ( int j = 0; j < 2; j++ )


{
System.out.print("\n");
// tick through the array
for ( int i = 2; i <= 12; i++)
{
System.out.print(totals[i][j] + " ");
}
}

System.out.print("\n\n");
}

private int rollDie()


{
// 0 <= randomNumber < 1
double randomNumber = java.lang.Math.random();

// 0 <= randomNumber < 6


randomNumber *= 6;

// cast to an int (lop off the fraction)


int choice = (int) randomNumber;

choice++; // change to 1-6

return (choice);
}
}
OUTPUT:
MELJU
import java.lang.*;

// one row for the cellular automaton OUTPUT:


class CARow
{
// how many cells in a row
private int rowLength;

// each cell is either alive (true)


// or dead (false)
private boolean[] rowData;

// the rules as an array of


// boolean values
private boolean[] rules;

// public constructor takes the length


// of the row
public CARow(int rowlen)
{
rowLength = rowlen;
rowData = new boolean[rowLength];
rules = new boolean[8];
}

// Private constructor called only by


// generation(). Makes a cloned row.
private CARow(int rowlen, boolean[] theRules)
{
rowLength = rowlen;
rowData = new boolean[rowLength];
rules = theRules;
}

// fill the row at random


void randomize()
{
for ( int i = 0; i < rowLength; ++i )
{
// the result of a conditional is a boolean, so we just assign it
rowData[i] = (java.lang.Math.random() > 0.5);
}
}

void setCell(int index, boolean value)


{
rowData[index] = value;
}

boolean getCell(int index)


{
return rowData[index];
}
MELJU
// The string should have some subset of the digits 0-7 in it.
// Other characters can be present too, if you like,
// but they will be ignored.
void setRules(String s)
{
for ( int i = 0; i < 8; ++i )
{
// If the character corresponding to the number is in the
// string, we set its rule, else we delete its rule.
int c = '0' + i;
int indexFound = s.indexOf(c);
boolean wasFound = indexFound != -1;
rules[i] = wasFound;
}
}

// this takes 3 cell indexes and returns the state of


// the next generation for the center cell
private boolean nextState(int left, int center, int right)
{
// First, calculate a number from 0-7 corresponding to the three cells
// read as a boolean value.
// If the cells are true false false, this will return 4.
int leftVal = rowData[left] ? 4 : 0;
int centerVal = rowData[center] ? 2 : 0;
int rightVal = rowData[right] ? 1 : 0;

// this is used as an index into the rule array


int currentState = leftVal + centerVal + rightVal;
return rules[currentState];
}

// this processes the current row according to the current rules


// and returns another row with the next generation and the same rules
public CARow generation()
{
// get a row
CARow newRow = new CARow(rowLength, rules);
// and now all the middle ones are easy
for ( int i = 1; i < rowLength - 1; ++i )
{
boolean newState = nextState(i-1, i, i+1);
newRow.setCell(i,newState );
}
// set the two end cells
newRow.setCell(0, nextState(rowLength-1, 0, 1));
newRow.setCell(rowLength-1, nextState(rowLength-2, rowLength-1, 0));

return newRow;
}
MELJU
// this gives us the nice ability to print these things easily as strings
public String toString()
{
// string buffers are faster
StringBuffer sb = new StringBuffer(rowLength);
for ( int i = 0; i < rowLength; ++i )
{
sb.append(rowData[i] ? '*' : ' ');
}
return new String(sb);
} OUTPUT:
}

public class OneDimensionalCA


{
// how many columns in our CA
public final static int NCOLS = 32;

// how many rows in our display


public final static int NROWS = 16;

public static void main(String[] args)


{

CARow row = new CARow(NCOLS);

if ( args.length >= 1 )
{
row.setRules(args[0]);
row.randomize();
}
else
{
// if no args are specified, do something pretty
// (namely, the Sierpinski's triangle fractal)
row.setRules("2345");
row.setCell(16, true);
}

for ( int i = 0; i < NROWS; ++i )


{
System.out.println(row);
row = row.generation();
}
}
}
MELJU
import java.util.*;

class Dog
{ OUTPUT:
public String name;
public int howNoisy;

public Dog(String name, int howNoisy)


{
this.name = name;
this.howNoisy = howNoisy < 5 ? howNoisy : 5;
}

public void bark()


{
for ( int i = 0; i < howNoisy; i++ )
{
System.out.print("Bark ");
}
}
}

class Employee
{
public String name;
public double salary;

// constructor initializes the members


public Employee(String name, double salary)
{ OUTPUT:
this.name = name;
this.salary = salary;
}
}

class ObjectArrayList
{

public void run()


{

ArrayList myList = new ArrayList();

// fill the ArrayList with Dogs


for ( int i = 0; i < 10; i++ )
{
String name = "Dog";
name += i;
myList.add(new Dog(name, i));
}
MELJU
OUTPUT:
// display the Dogs and ask them to bark()
System.out.print("\nFirst contents of myList...");
for ( int i = 0; i < 10; i++ )
{
Dog theDog = (Dog) myList.get(i);

System.out.print("\n" + theDog.name +
". Barks " + theDog.howNoisy + " times: ");
theDog.bark();
}

// clear the Dogs out of the ArrayList


myList.clear();

// fill the same ArrayList with Employee objects


for ( int i = 0; i < 1000; i++ )
{
String name = "Employee";
name += i;
myList.add(new Employee(name, i*10000));
}

// display the Employees


System.out.println("\n\nSecond contents of myList...");
for ( int i = 0; i < 1000; i++ )
{
System.out.println("Employee: " + ((Employee)myList.get(i)).name
+ ". Salary: " + ((Employee)myList.get(i)).salary);
}
} OUTPUT:

// the tester program


public static void main(String[] args)
{
ObjectArrayList oa = new ObjectArrayList();
oa.run();
}

}
MELJU
OUTPUT:

import java.util.*;

class Dog
{
public String name;
public int howNoisy;

public Dog(String name, int howNoisy)


{
this.name = name;
this.howNoisy = howNoisy < 5 ? howNoisy : 5;
}

*************************************************************************
MELJU
import java.util.*;

class Dog
{
public String name;
public int howNoisy;

public Dog(String name, int howNoisy)


{
this.name = name;
this.howNoisy = howNoisy < 5 ? howNoisy : 5;
} OUTPUT:

public void bark()


{
for ( int i = 0; i < howNoisy; i++ )
{
System.out.print("Bark ");
}
}

public String toString()


{
return "the dog " + name;
}
}

class Employee
{
public String name;
public double salary;

// constructor initializes the members


public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}

public String toString()


{
return "the Employee " + name;
}
}

class HeterogeneousArrayList
{

// the tester program


public static void main(String[] args)
{
HeterogeneousArrayList h = new HeterogeneousArrayList();
h.run();
}
MELJU
public void run()
{

ArrayList myList = new ArrayList();

// fill the ArrayList with Dogs


for ( int i = 0; i < 10; i++ )
{ OUTPUT:
String name = "Dog";
name += i;
myList.add(new Dog(name, i));
}

System.out.println("After adding dogs, " +


"myList.size(): " + myList.size());

// fill the same array with Employee objects


for ( int i = 0; i < 10; i++ )
{
String name = "Employee";
name += i;
myList.add(new Employee(name, i * 10000));
}

System.out.println("After adding Employees, " +


"myList.size(): " + myList.size());

for ( int i = 0; i < myList.size(); i++ )


{

Object o = myList.get(i);

System.out.println(o.toString() + " ");

// test if it is a Dog, if so, cast and bark


if ( o instanceof Dog )
{
Dog theDog = (Dog) o;
System.out.println(theDog.name +
". Barks " + theDog.howNoisy + " times.");
}

// test if it is an employee, if so cast and check salary


if ( o instanceof Employee )
{
System.out.println("Employee: " +
((Employee)myList.get(i)).name
+ ". Salary: " + ((Employee)myList.get(i)).salary);
}

}
}
}
MELJU
OUTPUT:

import java.util.*; OUTPUT:

class Employee
{
public String name;
public double salary;

// constructor initializes the members


public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
}
MELJU
class InsertInMidArrayList
{

// the tester program


public static void main(String[] args)
{
InsertInMidArrayList iim = new InsertInMidArrayList();
iim.run();
}

public void run()


{
ArrayList myList = new ArrayList();

// insert Employee objects into the center of the ArrayList


for ( int i = 0; i < 5; i++ )
{
String name = "Employee";
name += i;
myList.add(new Employee(name, i * 100));
}

// display the list


for ( int i = 0; i < myList.size(); i++ )
{
System.out.println("Employee: " +
((Employee)myList.get(i)).name
+ ". Salary: " + ((Employee)myList.get(i)).salary);
}

// insert an Employee at offset 3


System.out.println("\nInserting employee at offset 3");
myList.add(3,new Employee("EmployeeInTheMiddle", 7));

// re-display the list


for ( int i = 0; i < myList.size(); i++ )
{
System.out.println("Employee: " +
((Employee)myList.get(i)).name
+ ". Salary: " + ((Employee)myList.get(i)).salary);
} OUTPUT:
}
}
MELJU
import java.util.*;

class Employee OUTPUT:


{
public String name;
public double salary;

// constructor initializes the members


public Employee (String name, double salary)
{
this.name = name;
this.salary = salary;
}
}

class Dog
{
public String name;
public int howNoisy;

public Dog(String name, int howNoisy)


{
this.name = name;
this.howNoisy = howNoisy < 5 ? howNoisy : 5;
}

public void bark()


{
for ( int i = 0; i < howNoisy; i++ )
{
System.out.print("Bark ");
}
}

public String toString()


{
return this.name;
}
}

class SetAndRemoveInArrayList
{

// the tester program


public static void main(String[] args)
{
SetAndRemoveInArrayList a = new SetAndRemoveInArrayList();
a.run();
}

public void run()


MELJUN COR
{
ArrayList myList = new ArrayList();

// fill the array with Employee objects


for ( int i = 0; i < 10; i++ )
{
String name = "Employee";
name += i;
myList.add(new Employee(name, i * 10000));
}

// add a Dog object to the ArrayList


myList.add(5, new Dog("Spot", 4));

// size the array


int size = myList.size();

System.out.println("myList is now " + size + " elements long.");

for ( int i = 0; i < myList.size(); i++ )


{
Object o = myList.get(i);
if ( o instanceof Employee )
{
System.out.println("Employee: " +
((Employee)myList.get(i)).name + ". Salary: "
+ ((Employee)myList.get(i)).salary);
}
else if ( o instanceof Dog )
{
Dog theDog = (Dog) o;
System.out.println("Dog: " + theDog);
theDog.bark();
System.out.println("\nHey! Who let this dog in here?");
System.out.println("Removing dog at index: " + i + "\n");
myList.remove(i);
System.out.println("Continuing...\n");
}
}
// find the middle element and replace
size = myList.size();
int middle = size / 2;
System.out.println("Replacing element " + middle);
myList.set(middle, new Employee("New Employee!", 10000));

System.out.println("\nDisplaying the final contents of myList\n");


// show the array with the replaced element
for ( int i = 0; i < myList.size(); i++ )
{
System.out.println("Employee: " +
((Employee)myList.get(i)).name
+ ". Salary: " + ((Employee)myList.get(i)).salary);
}
}
}
MELJU
OUTPUT: