RU beehive logo ITEC Department logo
ITEC 120
2007spring
ibarland,
jpittges

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect14b
arrays

completed reading: Section 4.12; Chapter 6.
Reading: Chapters 8 (inheritance). (You can also skim Chapter 7 if you like; it is discussing approaches to good design.)

Arrays vs Lists

In practice, lists prove much more flexible than arrays: it's much more common to have data of the form “0 or more data” than “exactly 100 data”. ArrayList<Type> is almost always what you want, despite its slightly verbose name.

main

BlueJ has a rich interface for interacting with Java programs: you can call any method of any class. Most IDEs have a much more limited interface: They let you choose a certain class, but then you can only call one specific (static) method of that class:


/**
 * Write a description of class Acronym here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Acronym {

  /** A test driver which makes an acronym from its input,
   * printing the results to SYstem.out.
   * @param args The words of input.  Each String must be non-empty (and non-null).
   */
  public static void main( String[] args ) {
    System.out.println( "A " + args.length + "-letter acronym for "
                      + Acronym.wordsToString( args, " ", "\"", "\"" )
                      + " is "
                      + "\"" + Acronym.acronym(args) + "\""
                      + "." );
  }

  /* Return a single string, concatenating each word in an array of Strings.
   * @param words the individual Strings.
   * @param between What to put in between each word; usually " " or ", ".
   * @param before What to start the answer with; often "".
   * @param after What to finish the answer with; often "".
   */ 
  public static String wordsToString( String[] words, String between, String before, String after ) {
    String innards = "";
    if (words.length > 0) {
      innards += words[0];
      }
    for ( int i=1;  i < words.length;  ++i ) {
      innards += between + words[i];
      }
    return before + innards + after;
    }
    
  /** Return an acronym for an array-of-words, each letter capitalized.
   * and separated by a ".".
   * @param words An array of single words.  Each String must be non-empty.
   * @return an acronym for an array-of-words, each letter capitalized.
   */
  public static String acronym( String[] words ) {
    String asf = "";   // "acronym so far"
    for ( int i=0;  i < words.length;  ++i ) {
      asf += words[i].toUpperCase().charAt(0) + ".";
      }
    return asf;
    }
      
      
  }
There is nothing special about the method-name “main” except that it's been chosen as the de facto starting method by most IDEs. The input argument -- an array of Strings -- is a convention from the UNIX operating system. This input is the primary way your java program gets initial information from the operating system, when your java program is launched: a fixed number of words. For example, from a UNIX shell:
java Acronym hello, world

Review and different perspective



Like lists, but:
- Fixed size -- when the array is created with "new", its size is set in stone
- instead of "new LinkedList<String>()", a new syntax:
     "new String[50]"
- Instead of "l.get(7)", a new syntax: a[7]
- instead of "l.add("meow", 8)", a new syntax for the same thing: a[8] = "meow"
- instead of "l.add(..)", … nothing!  
   (You can't add new things to the end.)
- Instead of "l.size()", a new syntax: a.length

Why a new data structure, if a List can already do everything an array can, and yet the array is limited to a fixed size? Answer: For some data, the exact index of the data is also part of the information. For instance, consider the high temperature for each day in January. double[] is an appropriate type:

double[] temps = new double[31];
/* Here, have code which initializes all 31 elements of the array */

temps[5]    // Knowing that the high occured on Jan.06 is part of the data.
Also, sometimes the physical world corresponds to fixed-size collections:
class Motel {
  String name;
  String address;
  int numRooms = 57;
  Room[] rooms = new Room[this.numRooms];
  //...
  }

If a list is a line-up bag of suspects (er, objects), then an array is a bus of objects.

When creating an array, initialize all the fields immediately. If you can't, that's a good indication that you want to use a List instead.

(Note that when you add into the middle of a list, it changes what index each later object has. With an array, you can't insert into the middle, so that isn't an issue.)

When to use arrays vs lists Note: LinkedList, ArrayList 1 Processing arrays: for loops often very natural.

1Rule of thumb: - If you know exactly how big an array you'll need at the time you call new, use an array. This happens less often than people seem to think. If you can't initialize all locations of the array immediately then use a list instead. (Unwise to leave “null” references sitting in unused array locations; it's easy to use those array locations by mistake.) - Otherwise use a list. THe only difference is performance: - LinkedList is good if you'll be doing a lot of add and remove to places other than the end, and when any "get"s are coming in sequence. - ArrayList is good almost all the time, except If in doubt, ArrayList is the right default choice. We'll see, that you can actually declare your methods and varibles of being of type List. Only when you actually call new do you need to commit to a particular type of List.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Aug.27 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme