Arrays, Lists, and Exceptions
Objective
- Use arrays and
ArrayList
s. - Handle exceptions.
Summary
Arrays
Creation of an array involves three steps:
- Declaring the array
- Creating memory locations
- Putting values into the memory locations.
Declaration
Arrays in Java may be declared in either of two forms:
type arrayname[];
type[] arrayname;
int numbers[];
float averages[];
int[] counters;
float[] marks;
Note: The size of the array is not part the declaration.
Creation
After declaring an array, we need to create it in the memory. Java allows us to create arrays using the new
operator: arrayname = new type[size];
. For example:
numbers = new int[5];
averages = new float[10];
These statements create necessary memory locations for the arrays numbers
and averages
, and designate them as int
and float
respectively. The variable numbers
refers to an array of 5 integers and averages
refers to an array of 10 floating-point values.
It is also possible to combine the two steps—declaration and creation—into one as shown below:
int[] numbers = new int[5];
We can then assign values to the individual elements of the array:
numbers[0] = 35;
numbers[1] = 40;
...
numbers[4] = 19;
Initialization
We can initialize arrays automatically as they are declared: type[] arrayname = {list of values};
. For example:
int[] numbers = {35, 40, 20, 57, 19};
It is also possible to assign an array object to another. For example:
int[] a = {1, 2, 3};
int[] b;
b = a;
are valid in Java. Both arrays will have the same values as they reference the same memory location.
Length
In Java, all arrays store the allocated size in a public
field called length
. We can access the length of an array x
using x.length
. For example:
int noOfElements = x.length;
Array of Objects
Student[] students = new Student[5];
This creates an array of 5 elements that can hold references to Student
instances, but the instances are not yet created. To create the instances, we call a constructor for each Student
and store the object references in the individual elements of the array:
students[0] = new Student(“Ahmed”);
students[1] = new Student(“Ali”);
...
students[4] = new Student(“Zakia”);
ArrayLists
Unlike fixed-size arrays, ArrayList
s stretch as you add elements to them and shrink as you remove elements from them. The declaration: ArrayList<T> list;
declares list
as an ArrayList
collection that can store only objects of type T
where <T>
is a
placeholder for any non-primitive type. The actual ArrayList
is created using the new
operator:
ArrayList<T> list = new ArrayList<T>();
Now, list
is created but has no elements. Its size is zero, and will grow as we add elements to it. The following table shows some of the methods that you can use with an ArrayList
:
Method | Description |
---|---|
add() | Adds an element to the end of the ArrayList . |
clear() | Removes all the elements from the ArrayList . |
contains() | Returns true if the ArrayList contains the specified element; otherwise, returns false . |
get() | Returns the element at the specified index. |
indexOf() | Returns the index of the first occurrence of the specified element in the ArrayList . |
remove() | Overloaded. Removes the first occurrence of the specified value or the element at the specified index. |
size() | Returns the number of elements stored in the ArrayList . |
trimToSize() | Trims the capacity of the ArrayList to current number of elements. |
Exercise 1*
Using Arrays
-
Create a new project and add to it the following class:
ArrayApp.javaimport java.util.Scanner; public class ArrayApp { public static void main(String[] args) { int[] readings = new int[5]; Scanner scanner = new Scanner(System.in); for (int i = 0; i < readings.length; i++) { System.out.print("Enter element no. " + i + ": "); readings[i] = scanner.nextInt(); } scanner.close(); } }
-
Add a linear
search()
method that searches for a value in an integer array. The method returns the index of the first found value. If the value is not found, then the method returns-1
. Callers of this method should check the return value. Use the following signature:public static int search(int[] array, int value);
-
Add the method
replace()
that searches for a value in an integer array, and if found, then that value is replaced by another value. Let the method replace all occurrences of thesearchValue
with thereplaceValue
. Use the following signature:public static void replace(int[] array, int searchValue, int replaceValue);
-
Call the
replace()
method in yourmain()
method to replace every occurrence of the value2
with the value9
, and then print the array of elements to see if they were changed.
Exercise 2*
Arrays of Objects
-
Create a new project and reuse the
Circle
class from Exercise 5.1. -
Create a new class
CircleArrayTest
using the following code:CircleArrayTest.javaimport java.util.Scanner; public class CircleArrayTest { public static void main(String[] arg) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the size of the array: "); int size = scanner.nextInt(); Circle[] circles = new Circle[size]; for (int i = 0; i < circles.length; i++) { System.out.println("Enter the radius for circle #" + i + ": "); double radius = scanner.nextDouble(); circles[i] = new Circle(radius); } System.out.println("Circles list: "); // write code to print the radius, area, and circumference // for all the circles, each on a separate line. scanner.close(); } }
-
Write code to print the radius, area, and circumference for all the circles, each on a separate line.
-
In the
CircletArrayTest
class, add a static method calledfindLargest(Circle[] circles)
that returns theCircle
with the “largest” radius in the array parameter; if there are more than one such circle, return any one of them. Use afor-each
loop. -
In the
main()
method write a statement to print all the details of the circle that has the largest radius.
Exception Handling
In the above main()
method, if the user enters a non-numeric value for the radius an exception called InputMismatchException
will be thrown. Use a try
/catch
block to handle that exception: display an error message and assign zero values to the radius, so your program will not terminate and continue to read data for the next circle.
Exercise 3*
ArrayList
s
-
Create a new project with the following class then run it:
ArrayListCollection.javaimport java.util.ArrayList; public class ArrayListCollection { public static void main(String[] args) { // create a new ArrayList of Strings with an initial capacity of 10 ArrayList<String> items = new ArrayList<String>(); items.add("red"); // append an item to the list items.add(0, "yellow"); // insert the value at index 0 // header System.out.print("Display list contents using a counter-controlled loop:"); // display the colors in the list for (int i = 0; i < items.size(); i++) { System.out.printf(" %s", items.get(i)); } // display colors using foreach in the display method display(items, "\nDisplay list contents using a for-each loop:"); items.add("green"); // add "green" to the end of the list items.add("yellow"); // add "yellow" to the end of the list display(items, "List with two new elements:"); items.remove("yellow"); // remove the first "yellow" display(items, "Remove first instance of \"yellow\":"); items.remove(1); // remove item at index 1 display(items, "Remove second list element (\"green\"):"); // check if a value is in the List System.out.printf("\"red\" is %sin the list%n", items.contains("red") ? "" : "not "); // display number of elements in the List System.out.printf("Size: %s%n", items.size()); } // end main // display the ArrayList's elements in the console public static void display(ArrayList<String> items, String header) { System.out.print(header); // display header // display each element in items for (String item : items) { System.out.printf(" %s", item); } System.out.println(); // display end of line } // end method display } // end class ArrayListCollection
-
Add a static method
getRepeatCount(ArrayList<String> list, String value)
. Let the method return how many times the stringvalue
exists in thelist
. Test the method by finding how many"red"
’s are in the items list of themain()
method.
Exercise 4
- In the
CircleArrayTest
class from Exercise 2, add a static method calledgetAverageArea(Circle[] circles)
that returns the average area of all circles. Use afor-each
loop. - In the
main()
method get and print the average circle area. - Add an instance method called
enlarge()
that takes adouble
scaleFactor
as parameter and if it is greater than1
, it multiplies the radius of the circle by thisscaleFactor
. If thescaleFactor
is less than or equal to1
it does nothing. - Add a static method called
scaleUp(Circle[] circles)
that enlarges each circle in the circles array using a random integer between2
and9
, inclusive. - Use the above methods to
scaleUp()
all the circles in yourCircleArrayTest
. Print the average area after the update.
Exercise 5+
Develop a GradeBook
class that instructors can use to maintain students’ grades on an exam and display a grade report that includes the grades, class average, lowest grade, and highest grade.
Create a package called event
with two classes: GradeBook
and GradeBookTest
. GradeBook
has has two fields: a course title and grades for exam in an array, including the setters, getters, and the fully parameterized constructor. The following is an implementation of GradeBookTest
:
public class GradeBookTest {
public static void main(String[] args) {
int[] grades151 = {90, 50, 70, 80, 100, 90, 50, 70,
80, 95, 90, 55, 75, 85, 100};
GradeBook gradeBook = new GradeBook("Programming Concepts", grades151);
display(gradeBook);
System.out.println("Minimum Grade: " + gradeBook.minimum());
System.out.println("Maximum Grade: " + gradeBook.maximum());
System.out.println("Average Grade: " + gradeBook.average());
}
/* Write a method to display the course title and all its grades */
/* Write a method to find the minimum grade in a list of GradeBooks */
/* Write a method to find the maximum grade in a list of GradeBooks */
/* Write a method to find the average grade in a list of GradeBooks */
}
After you have created GradeBook
, implement the missing parts in GradeBookTest
so that it runs correctly.
Exercise 6+
List
of Circles
Reimplement CircleArrayTest
from Exercise 4 in another class CircleListTest
using a List
and ArrayList
instead of an array.
Exception Handling
In the main()
method, calling getAverageArea()
may return ArithmeticException
if the list is empty. Use a try
/catch
block to handle this exception by displaying an error message so your program will not abruptly terminate.