Array of Objects
Array of Objects
Array of Objects
Objectives
basic operations supported by an array.
print all the array elements(objects)
Adds an object at the given index.
Deletes an object at the given index.
Searches an object using the given index or by
the value.
Updates an object at the given index.
Case study
Problem: A antique
shop that sells antique items, namely vases, statues, and
paintings. The owner can add item to inventory. The shop will keep items in the
list. The owner can add a new item to it, he search also the item,….
=>For now, we want to manage the list of objects such as vases, statues,
paintings in an array.
Case study
Case study
public class Item
{ // declare fields
protected int value; // the price of a Item (>=0)
protected String creator; // the creator who creates the item( is not empty)
//constructors
public Item(){ value=0; creator=""; }
public Item(int value, String creator){
this.value=value;
this.creator=creator;
}
//getters,setters: you is required to add more code to get/set fields of a Item object
//this method is used to input all fields of a Item object
public void input(){
//use Scanner class to input fields
//use try..catch/throws to handle exceptions
}
//this method returns a string that includes value, creator of a Item object
public String toString(){
//return
}
}
Case study
public class Vase extends Item
{
private int height;//height of a vase (>=0 and <=2000)
private String material;//material of a vase (is not empty)
//TODO: you add more your codes
//constructors
//getter
//setter
//this method is used to input all fields of a Vase object
public void input(){
//use Scanner class to input fields
//use try..catch/throws to handle exceptions
}
//this method returns a string that includes value, creator, height, material of a
vase object
public String toString(){
//return ;
}
}
Case study
//this method removes the item at the specified position in this list.
//Shifts any subsequent elements to the left
//input: the index you wish to remove
pulic boolean removeItem(int index){
if( index >= 0 && index < numOfItem){
for(int j=index; j< numOfItem; j++ ){
list[j]=list[j+1];
}
numOfItem --;
return true;
}
return false;
}
Case study
//this method prints out all items that belong to the given type in the list.
public void displayItemsByType(String type){
if (type.equals("Vase")){
for(int i=0; i < numOfItem; i++)
if ( list[i] instanceof Vase) System.out.println( list[i]);
}
else if (type.equals("Statue")){
for(int i=0; i < numOfItem; i++)
if ( list[i] instanceof Statue) System.out.println( list[i]);
}
else {
for(int i=0; i < numOfItem; i++)
if ( list[i] instanceof Painting) System.out.println( list[i]);
}
}
Case study
}//end class
Case study
case 1:
Item tmp=new Vase();
tmp.input();
if(obj.addItem(tmp)){
System.out.println("added");
}
break;
case 2:
…..
break
case 3:
….
break;
…..
}//end switch
} while(choice<=9); //end while
} //end class