Length i if personigetage personminidxgetage

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: essing – Sample 2 • 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 Page 17 11/2/2008 Object Deletion – Approach 1 int delIdx = 1; A A Delete Person B by Delete Person B by setting the reference in setting the reference in position 11to null. position to null. person[delIdx] = null; person person 0 A A 1 B B 2 C C 3 D D Before A is executed A Page 18 0 A A 1 2 C C 3 D D After A is executed A 11/2/2008 Object Deletion – Approach 2 int delIdx = 1, last = 3; A A Delete Person B by Delete Person B by setting the reference in setting the reference in position 11to the last position to the last person. person. person[delIndex] = person[last]; person[last] person = null; person 0 A A 1 B B 2 C C 3 D D Before A is executed A Page 19 0 A A 1 D D 2 3 C C After A is executed A 11/2/2008 Person Array Processing – Sample 3 • 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); } Pag...
View Full Document

This document was uploaded on 03/03/2014.

Ask a homework question - tutors are online