Lesson Set Arrays and Collections 6 CLO-1: Lab 5 Submitted By: Syed Najeem Shah CMS ID:49447 DEP:SE2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Lab 5

Submitted by : Syed Najeem Shah


CMS ID :49447 DEP
:SE2

Lesson Set Arrays and Collections 6 CLO-1

Purpose 1. Manipulate a collection of data


values, using an array
2. Define a method that accepts an array as its parameter and
a method that returns an array.
3. Describe how a two-dimensional array is implemented as
an array of arrays.
4. Manipulate a collection of objects, using lists and maps.

Procedure 5. Students should read the Pre-lab Reading Assignment


before coming to lab.
6. Students should complete the Pre-lab Writing Assignment
before coming to lab.
7. In the lab, students should complete Labs 1.1 through 1.4
in sequence.
8. Your instructor will give further instructions as to grading
and completion of the lab.
9. Students should complete the set of lab tasks before the
next lab and get them checked by their lab instructor.
Contents Pre-requisites Completion
Time

Pre-lab Reading Assignment - 10 min


Lab 1 30 min
Basic
Basic Jfame Class understanding of
GUI
Lab 2 30 min
Basic
GUI and Events understanding of
Events
Lab 3 30 min
Programming
Fundamentals
Introduction: People collect all sorts of items from bottle caps to exotic cars. For proof, just go
toeBay (www.ebay.com) and see millions and millions of collectibles up for
auction.

With computers, people amass intangible items such as music files. Exactly how
many MP3 files do you have on your computer? Probably in the hundreds and
you lost track of exactly how many. You may want to develop a custom software,
so you can store the information you want in the format you like, to keep track of
all MP3 files downloaded from the Web.

When we write a program to deal with a collection of items, say, 500 Student
objects, 200 integers, 300 MP3 files, and so forth, simple variables will not work.
It
is just not practical or feasible to use 500 variables to process 500 Student objects.
In theory, you can, but honestly, do you want to type in identifiers for 500
variables
(student1, student2, . . .)? A feature supported by programming languages to
manipulate a collection of values is an array.
In this chapter we will learn about Java arrays. We will learn the basics of array
manipulation and how to use different types of arrays properly and effectively. In
addition, we will study several collection classes from the java.util package that
provide more advanced data management features not found in the basic Java
arrays.
Array Basics:
Suppose we want to compute the annual average rainfall from 12 monthly
averages.
We can use three variables and compute the annual average as follows (in this
and other code fragment examples, we assume scanner is a properly declared
and created Scanner object):

double sum, rainfall, annualAverage; sum


= 0.0;
for (int i = 0; i < 12; i++) {
System.out.print("Rainfall for month " + (i+1) + ": ");
rainfall = scanner.nextDouble(); sum += rainfall;
}
annualAverage = sum / 12.0;
Now suppose we want to compute the difference between the annual and monthly
averages for every month and display a table with three columns, similar to the
one shown in Figure 10.1.
To compute the difference between the annual and monthly averages, we need
to remember the 12 monthly rainfall averages. Without remembering the 12
monthly
averages, we won’t be able to derive the monthly variations after the annual
average
is computed. Instead of using 12 variables januaryRainfall, februaryRainfall, and so
forth to solve this problem, we use an array.

An array is a collection of data values of the same type. For example, we may
declare an array consisting of double, but not an array consisting of both int and
double. The following declares an array of double: double[] rainfall;

The square brackets indicate the array declaration. The brackets may be attached to
Array: a variable instead of the data type. For example, the declaration double
rainfall[]; is equivalent to the previous declaration. In Java, an array is a
reference data type. Unlike the primitive data type, the amount of memory
allocated to store an array varies, depending on the number and type of values in
the array. We use the new operator to allocate the memory to store the values in an
array. Although we use
Array Decleration:
the same reserved word new for the array memory allocation as for the creation
of a new instance of a class, strictly speaking, an array is not an object.

The following statement allocates the memory to store 12 double values and
associates the identifier rainfall to it.
rainfall = new double[12]; //create an array of size 12 Figure
10.2 shows this array.
We can also declare and allocate memory for an array in one statement, as in
double[] rainfall = new double[12];

Using constants to declare array sizes does not always lead to efficient space
usage.
We call the declaration of arrays with constants a fixed-size array declaration.
Fixed sizearray There are two potential problems with fixed-size array declarations.
declearion: Suppose, for example, we declare an integer array of size 100: int[] number
= new int[100];
The first problem is that the program can process only up to 100 numbers. What if
we need to process 101 numbers? We have to modify the program and compile it
again. The second problem is a possible underutilization of space. The above
declaration allocates 100 spaces whether they are used or not
Lab Tasks

1. What is the output from the following code?


List<String>list = new ArrayList<String>();
for(int i = 0; i < 6; i++) { list.add("element
" + i); System.out.println(list.size());
}
OUTPUT

2. What is the output from the following code?


List<String>list = new ArrayList<String>();
for(int i = 0; i < 6; i++) {
list.add("element " + i);
}
list.remove(1); list.remove(3);
System.out.println(list.get(2))
OUTPUT

3. Consider the following Thesaurus class:


class Thesaurus {
//Returns all synonyms of the word as a Set
//Returns null if there is no such word public
java.util.Set<String>get (String word){...}
//Returns all key words in this thesaurus as a Set
//returns an empty set if there are no keys (if you
//don't do anything, default behavior of
the //underlying JCF class will handle it)
public java.util.Set<String>keys( ){...}
//Adds 'synonym' to the synonym set of 'word'
//Pay close attention to this method. public
void put (String word, String synonym){...}
}

The get method returns a set of all synonyms of a given word. The keysmethod returns all key
words in the thesaurus. The put method adds anew synonym to the given word. Make sure to
handle the cases whenthe word already has a synonym list and when the word is added for thefirst
time. Using this Thesaurus class, we can write, for example, thisprogram:

class SampleMain { public static void


main(String[] args) {
Thesaurus t = new Thesaurus();
t.put("fast", "speedy");
t.put("fast", "swift");
t.put("slow", "sluggish");
Set<String>synonyms = t.get("fast");
System.out.println(synonyms);
System.out.println(t.keys());
}
}
When the sample program is executed, the output will be

You might also like