Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Array operations

This page demonstrates some frerquently encountered operations on arrays.

 

 

 

 

The elements will be 0 - 9

You can make the array bigger but then it will be tedious to test algorithms which can fill the array beyond SIZE.

pos and data are declared here so can be accessed inside any method of the class - similar to global variables.

 

 

 

 

A mono-spaced font looks more "natural" (to me) when printing numbers.

 

 

 

 

 

 

 

 

 

pos is the last occupied element.

 

Recall that \n is a newline character.

 

 

increment position counter, add element.

 

 

 

 

 

 

 

 

 

 

 

You will probably need to make use of the String.split() method to do this - see the Strings page .

 

Consider the relative efficiency of the two add and delete methods. Which require more time? Suppose the array size was set to 1 million entries - would the choice of add methods make a difference?

 

Here is the source code for a framework Applet for this problem...

 

 

This exercise will give you a chance to think about the main algorithms you will need.  It will be an excellent idea to plan your solutions on paper before attempting to actually code the program.

 

 

For these exercises, we are going to use the same basic structure - an integer array called data. The basic starting Applet is as follows:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
* ArrayOps Class used to illustrate basic operations
* on arrays.
*
*/

public class ArrayOps extends Applet implements ActionListener
{

    // Define the array with 10 elements
    private static final int SIZE = 10;
   int data[] = new int[SIZE];

   // GUI objects
    TextArea display = new TextArea(5,40);
   TextField input = new TextField(5);
   Label messages = new Label("Information appears here");
   Button add = new Button("Add");
   Button show = new Button("Show array");

   // keep track of current number of elements in array
   private int pos = -1;
  
/**
   * Initialise Applet
   *
   */

   public void init()
   {
     add.addActionListener(this);
     show.addActionListener(this);
     add(display);
     add(add);
     add(show);
     add(input);
     add(messages);
     Font myFont = new Font("Courier", Font.BOLD, 12);
     display.setFont(myFont);
   }
  
/**
   * Detect button presses
   *
   *@param the event that caused the method to be called
   */

   public void actionPerformed( ActionEvent e )
   {
     if(e.getSource() == show)
     {
       displayScores();
     }
     else
     {
       addValue();
     }
   }
  
/**
   * Show array contents in TextArea
   */

   public void displayScores()
   {
     // displays the array contents in the text area
     display.setText("");
     for (int i = 0; i <= pos; i++)
     {
       display.append(data[i] + " ");
     }
     display.append("\nend of data");
   }
  
/**
   * Add element to array
   */

   public void addValue()
   {
     pos = pos + 1;
     data[pos] = Integer.parseInt(input.getText());
   }
}

Exercises

Add a "clear" button which "empties" the array of values. Hint: you don't need to remove any data values from the array to do this.

The add element procedure does not give an error if the user tries to add more than SIZE elements to the array. Fix this problem.

Add a message after "end of data" which gives the current number of elements in the array.

Add a button "delete" which allows the user to delete the last number in the array. Set the value of a deleted element to -1.

Allow the user to specify which element they want to set to -1 (ie mark as deleted)

When a number is subsequently added, make sure the array is first checked to see if there is a -1 position available, before adding at the end.

Add a new button "compact" which removes all -1 elements from the array by shuffling down elements from the end. Don't forget to update pos. Removing 1 element is not too bad, removing 2 or 3 is a bit trickier.

Add a new button "edit" which allows you to change any specified array element to a new value - you could enter the position and new value in the box, eg 2 21.

Change the delete function so that it "shuffles" over the deleted value instead of just marking it with -1.

Change the add function so that it adds items in correct order. Hint , try shuffling from the top down to the insertion point, it's much easier.

Remember that pos will need adjustment in these methods to add and delete values.

 

Write an Applet that examines an array SCORES and a parallel array NAMES .  The program deletes any names from the NAME array for which the scores are less than 45.  First phase, delete by replacing the name with the String "XXXXX". Second phase shuffle up the names to compact the array, end list of names with "XXXXX".  For example, initially:

SCORES

23

19

56

99

43

82

 

0

1

2

3

4

5

NAMES

fred

june

sayaka

richard

jenny

mikk

 

0

1

2

3

4

5

after phase 1:

NAMES

XXXXX

XXXXX

sayaka

richard

XXXXX

mikk

 

0

1

2

3

4

5

after phase 2:

NAMES

sayaka

richard

mikk

XXXXX

   
 

0

1

2

3

4

5

 

Related: [ Java home | Previous: Object Arrays | Next: 2D Arrays ]

All about manipulating arrays.


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009