teaching machines

CS 245 Lab 3 – Interfaces

September 18, 2013 by . Filed under cs245, fall 2013, labs.

First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab.

Don’t forget to work in pairs! Where possible, please work with someone that you did not work with last week. The exchange of new ideas and perspectives is not an opportunity you want to rob yourself of.

Synopsis

In this lab, you will continue to explore the use of interfaces so that you can write code that will operate on many different subtypes of some supertype. A primary of advantage of interfaces is that you can exploit a bunch of code in the Java library (like filtering only files that meet some criteria or sorting) but use your custom classes.

Checkpoint 1

Let person A type.

Check out the documentation for java.io.FileFilter or java.io.FilenameFilter. See how these types are used by the methods of java.io.File. Also put Arrays.toString and File.length in your toolbelt.

Write a method named listLarge that accepts a path to a directory as a parameter. It prints to the console all files in the directory that are larger than some threshold number of bytes.

Write a method named listImages that accepts a path to a directory as a parameter. It prints to the console all files in the directory that are JPEGs, PNGs, BMPs, or GIFs.

Kudos and high-fives if you also print out matching files in all subdirectories. It shouldn’t take more than a couple extra lines of code.

Checkpoint 2

Let person B type.

Sorting is one of those algorithms that’s really nice to write once but apply to many different sortable objects. This is only possible if the generic sorting routine can be customized with our sorting criteria. After all, some of us want to sort from smallest to largest, others from largest to smallest, others by height, others by names, others by income, and so on. The Comparator interface allows this to happen. Check out what methods this interface imposes on its implementers.

Say you’ve got an array of Planets, storing for each planet a composite object holding each planet’s name, its mean distance from the sun in AU, and its mass relative to Earth:

Planet[] planets = {
  new Planet("Saturn", 9.5, 95.0),
  new Planet("Earth", 1.0, 1.0),
  new Planet("Venus", 0.7, 0.815),
  new Planet("Jupiter", 5.2, 318.0),
  new Planet("Uranus", 19.6, 14.0),
  new Planet("Neptune", 30.0, 17.0),
  new Planet("Mars", 1.5, 0.107),
  new Planet("Mercury", 0.4, 0.055)
};

You can sort this array using Arrays.sort(yourArray, yourComparator). Sort the array in two different ways of your own choosing. Print out the results after each sort.