Arrays of Objects
• In Java, in addition to create arrays of
primitive data types (int, double,
float, char etc), we can declare arrays
of objects
• An array of primitive data is a powerful tool,
but an array of objects is even more powerful.
• The use of an array of objects allows us to
model the application more cleanly and
logically.
Declaring an Object Array
Code AA Person[ ] persons;
Only
Onlythe
thename
nameperson
personisis
persons = new Person[20];
declared,
declared,no
noarray
arrayisis
persons[0] = new Person( ); allocated
allocatedyet.
yet.
persons
State
of
Memory
After AA is executed
Creating an Object Array
Person [ ] persons = new Person[20];
Code Person[ ] persons; Now
Nowthe
thearray
arrayfor
forstoring
storing20
20
Person objects is created,
Person objects is created,
BB persons = new Person[20]; but
butthe
thePerson
Personobjects
objects
themselves
themselves are notyet
are not yet
persons[0] = new Person( );
created.
created.
person
persons
0 1 2 3 4 16 17 18 19
State
of
Memory
After BB is executed
Creating an Object Array
Code Person[ ] persons;
One
OnePerson
Personobject
objectisiscreated
created
persons = new Person[20]; and the reference to this
and the reference to this
object
objectisisplaced
placedininposition
position0.0.
CC persons[0] = new Person( );
person
0 1 2 3 4 16 17 18 19
State
of Person
Memory
After CC is executed
Creating an Object Array
Code 20
for(int i=0;i<persons.length;i++) 20Person
Personobjects
objectsareare
D
D persons[i] = new Person( );
created
to
and the reference
created and the reference
tothese
theseobjects
objectsare
areplaced
placed
ininposition 0 to 19.
position 0 to 19.
person After D
D is executed
0 1 2 3 4 16 17 18 19
State
of
Person
Person
Person
Person
Person
Person
Person
Person
Person
Memory
Array of Object - Sample
public class Rectangle
{
private int length,width,area;
public Rectangle (int l, int w){
length = l;
width = w;
}
public void calculateArea() {
area = length * width;
}
public int getArea() {
return area;
}
} // end class
Array of Object- Sample
import java.util.*;
public class TestRectangle{
public static void main (String []args)
{
static Scanner console = new Scanner(System.in);
Rectangle rect[]=new Rectangle[2];
for (int j=0;j<rect.length;j++){
System.out.print("Length : ");
int length = console.nextInt();
System.out.print("Width: ");
int width = console.nextInt();
rect[j]=new Rectangle(length,width);
rect[j].calculateArea();
System.out.println("Area of Rectangle " + (j+1) + " = " +
rect[j].getArea());
System.out.println();
}
}
}//end class
Array of Object- Sample
import java.io.*;
class Person
{
private String name;
private int age;
private char gender;
public Person(String newName, int newAge, char newGender){
name = newName;
age = newAge;
gender = newGender;
}
Array of Object- Sample
public String getName(){
return name;
}
public int getAge()
{
return age;
}
public char getGender()
{
return gender;
}
}
Array of Object- Sample
class PersonList{
private Person [] person;
private int counter;
public PersonList(int size){
person = new Person[size];
counter = 0;
}
public void addRecord(Person pers) {
person[counter] = pers
counter++;
}
public void displayRecord(){
for (int i= 0; i< counter; i++){
System.out.println("\nName ="+person[i].getName());
System.out.println("Age = "+person[i].getAge());
System.out.println("Gender = "+person[i].getGender());
}
}
} // end PersonList
Array of Object- Sample
import java.util.*;
public class TestPerson {
public static void main(String[] arg){
Scanner read = new Scanner(System.in);
String name=null; Person human;
int age;
char gender;
System.out.println("Enter number of person: ");
int num = read.nextInt();
PersonList people = new PersonList(num);
System.out.println("\n");
for (int i= 0; i< num; i++) {
System.out.print("\nEnter name = ");
name = read.next();
System.out.print("Enter age = ");
age = read.nextInt();
System.out.print("Enter gender = ");
gender = read.nextLine().charAt(0);
human = new Person(name, age, gender)
people.addRecord(human);
}
people.displayRecord();
}
} // end TestPerson
Array of Object- Sample
Output:
Enter number of person: 2
Enter name = MuthuSamy a/l Acaphan
Enter age = 23
Enter gender = male
Enter name = Siti Sarah binti Zakaria
Enter age = 19
Enter gender = female
Name = MuthuSamy a/l Acaphan
Age = 23
Gender =m
Name = Siti Sarah binti Zakaria
Age = 19
Gender =f
Process Exit...
Array of Object- Sample
• Find the youngest and oldest persons.
int minIdx = 0; //index to the youngest person
int maxIdx = 0; //index to the oldest person
for (int i = 1; i < person.length; i++) {
if ( person[i].getAge() < person[minIdx].getAge() ) {
minIdx = i; //found a younger person
} else if (person[i].getAge() > person[maxIdx].getAge() ) {
maxIdx = i; //found an older person
}
}
//person[minIdx] is the youngest and person[maxIdx] is the oldest
Array of Object- Sample
Object Deletion – Approach 1
Delete
DeletePerson
PersonBBbybysetting
setting
AA int delIdx = 1; the
the reference in position11toto
reference in position
person[delIdx] = null; null.
null.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA CC DD
Before AA is executed After AA is executed
Array of Object- Sample
Object Deletion – Approach 2
AA int delIdx = 1, last = 3; Delete
DeletePerson
PersonBBbybysetting
setting
person[delIndex] = person[last]; the
the reference in position11toto
reference in position
the
thelast
lastperson.
person.
person[last] = null;
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA DD CC
Before AA is executed After AA is executed
Array of Object- Sample
• Searching for a particular person. Approach 2 Deletion is used.
int i = 0;
while ( person[i] != null && !person[i].getName().equals("Latte") ) {
i++;
}
if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}
Array of Object- Sample
Object Deletion – Approach 1
Delete
DeletePerson
PersonBBbybysetting
AA int delIdx = 1; the
setting
the reference in position11toto
reference in position
person[delIdx] = null; null.
null.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA CC DD
Before AA is executed After AA is executed
Array of Object- Sample
Object Deletion – Approach 2
AA int delIdx = 1, last = 3; Delete
DeletePerson
PersonBBbybysetting
setting
person[delIndex] = person[last]; the
the reference in position11toto
reference in position
the
thelast
lastperson.
person.
person[last] = null;
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA DD CC
Before AA is executed After AA is executed