Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Datastructures and algorithms, Part 1

Explore datastructures, algorithms, flowcharts, pseudocode, and arrays

  • Print
  • Feedback

Page 4 of 7

AlarmClock [] ac = new AlarmClock [1];
Clock [] c = ac;
c [0] = new Clock ();


The compiler compiles the code fragment above because each line is legal. At runtime, however, c [0] = new Clock (); results in an ArrayStoreException. That exception occurs because we might try to access an AlarmClock-specific member via a reference to a Clock object. For example, suppose AlarmClock contains a public void soundAlarm() method, Clock lacks that method, and the code fragment above executes without throwing an ArrayStoreException object. An attempt to execute ac [0].soundAlarm (); crashes the JVM because we attempt to execute that method in the context of a Clock object (which doesn't incorporate a soundAlarm() method).

Caution
Exercise caution when accessing array elements because you might receive an ArrayIndexOutOfBoundsException or an ArrayStoreException.


Linear-search, bubble-sort, and binary-search algorithms

Developers commonly write code to search for data items in one-dimensional arrays and sort (order) those arrays. Three commonly used algorithms for performing those tasks are linear-search, binary-search, and bubble-sort.

The linear-search algorithm searches a one-dimensional array for a specific data item. The search first examines the element at index 0 and continues examining successive elements until either the data item is found or no more elements remain to examine. The following pseudocode demonstrates this algorithm:

  • Print
  • Feedback

Resources