0% found this document useful (0 votes)
4 views

Lesson 6 Arrays and Array List Classes

Chapter 7 covers arrays and the ArrayList class in Java, detailing their creation, initialization, and various operations. It explains how to process array contents, pass arrays as arguments, and introduces two-dimensional arrays and ragged arrays. The chapter also discusses the ArrayList class, highlighting its dynamic nature compared to traditional arrays.

Uploaded by

Fethulmubin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lesson 6 Arrays and Array List Classes

Chapter 7 covers arrays and the ArrayList class in Java, detailing their creation, initialization, and various operations. It explains how to process array contents, pass arrays as arguments, and introduces two-dimensional arrays and ragged arrays. The chapter also discusses the ArrayList class, highlighting its dynamic nature compared to traditional arrays.

Uploaded by

Fethulmubin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Chapter 7

Arrays and the ArrayList Class


Chapter Topics (1 of 2)

Introduction to Arrays
Processing Array Contents
Passing Arrays as Arguments to Methods
Some Useful Array Algorithms and Operations
Returning Arrays from Methods
String Arrays
Arrays of Objects
Chapter Topics (2 of 2)

The Sequential Search Algorithm


Parallel Arrays
Two-Dimensional Arrays
Arrays with Three or More Dimensions
The Selection Sort and the Binary Search
Command-Line Arguments
The ArrayList Class
7.1 Introduction to Arrays

• Primitive variables are designed to hold only one value at a time.


• Arrays allow us to create a collection of like values that are indexed.
• An array can store any type of data but only one type of data at a time.
• An array is a list of data elements.
Creating Arrays (1 of 3)
• An array is an object so it needs an object reference.

• The next step creates the array and assigns its address to the
numbers variable.
Creating Arrays (2 of 3)

• It is possible to declare an array reference and create it in


the same statement.

• Arrays may be of any type.


Creating Arrays (3 of 3)
• The array size must be a non-negative number.
• It may be a literal value, a constant, or variable.

• Once created, an array size is fixed and cannot be


changed.
Accessing the Elements of an Array

• An array is accessed by:


– the reference name
– a subscript that identifies which element in the array
to access.

• This array would have indexes 0 through 5.


Array Initialization

• When relatively few items need to be initialized, an


initialization list can be used to initialize the array.

• The numbers in the list are stored in the array in order:


– days[0] is assigned 31,
– days[1] is assigned 28,
– days[2] is assigned 31,
– days[3] is assigned 30,
– etc.
• See example: ArrayInitialization.java
Alternate Array Declaration
• Previously we showed arrays being declared:

– However, the brackets can also go here:

– These are equivalent but the first style is typical.


• Multiple arrays can be declared on the same line.

• With the alternate notation each variable must have brackets.

– The scores variable in this instance is simply an int variable.


7.2 Processing Array Contents

• Processing data in an array is the same as any other


variable.

• Pre and post increment works the same:

• Array elements can be used in relational operations:


Array Length
• Arrays are objects and provide a public field named length
that is a constant that can be tested.

– The length of this array is 25.


• The length of an array can be obtained via its length
constant.

– The variable size will contain 25.


The Enhanced for Loop

• Simplified array processing (read only)


• Always goes through all elements
• General format:
Array Size)

• You can let the user specify the size of an array:

• See example: DisplayTestScores.java


Reassigning Array References (1 of 2)

• An array reference can be assigned to another array of


the same type.

• If the first (10 element) array no longer has a reference to


it, it will be garbage collected.
Reassigning Array References (2 of 2)
Copying Arrays (1 of 2)

• This is not the way to copy an array.

Example: SameArray.java
Copying Arrays (2 of 2)
• You cannot copy an array by merely assigning one reference
variable to another.
• You need to copy the individual elements of one array to
another.

• This code copies each element of firstArray to the


corresponding element of secondArray.
Passing Arrays as Arguments

• Arrays are objects.


• Their references can be passed to methods like any other
object reference variable.

Example: PassArray.java
Comparing Arrays

• The == operator determines only whether array


references point to the same array object.
Comparing Arrays: Example
Useful Array Operations (1 of 2)
• Finding the Highest Value

• Finding the Lowest Value


Useful Array Operations (2 of 2)
• Summing Array Elements:

• Averaging Array Elements:

• Example: SalesData.java, Sales.java


Arrays and Files (1 of 2)

• Saving the contents of an array to a file:


Arrays and Files (2 of 2)

• Reading the contents of a file into an array:


Returning an Array Reference

• A method can return a reference to an array.


• The return type of the method must be declared as an array of
the right type.

• The getArray method is a public static method that returns


an array of doubles.
• See example: ReturnArray.java
7.6 String Arrays (1 of 3)
• Arrays are not limited to primitive data.
• An array of String objects can be created:

Example: MonthDays.java
7.6 String Arrays (2 of 3)

• If an initialization list is not provided, the new keyword


must be used to create the array:
7.6 String Arrays (3 of 3)

• When an array is created in this manner, each element


of the array must be initialized.
The length Field & the length Method
• Arrays have a final field named length.
• String objects have a method named length.
• To display the length of each string held in a String array:

• An array’s length is a field


– You do not write a set of parentheses after its name.
• A String’s length is a method
– You do write the parentheses after the name of the String
class’s length method.
7.7 Arrays of Objects (1 of 2)

• Because Strings are objects, we know that arrays can


contain objects.
7.7 Arrays of Objects (2 of 2)
• Each element needs to be initialized.

• See example: ObjectArray.java


7.10 Two-Dimensional Arrays (1 of 2)

• A two-dimensional array is an array of arrays.


• It can be thought of as having rows and columns.
7.10 Two-Dimensional Arrays (2 of 2)
• Declaring a two-dimensional array requires two sets of brackets
and two size declarators
– The first one is for the number of rows
– The second one is for the number of columns.

• The two sets of brackets in the data type indicate that the scores
variable will reference a two-dimensional array.
• Notice that each size declarator is enclosed in its own set of
brackets.
Accessing Two-Dimensional Array
Elements

Accessing one of the elements in a two-dimensional array


requires the use of both subscripts (row and column).
Accessing Two-Dimensional Array
Elements
• Programs that process two-dimensional arrays can do so with nested
loops.
• To fill the scores array:
Initializing a Two-Dimensional Array (1 of 2)
• Initializing a two-dimensional array requires enclosing each
row’s initialization list in its own set of braces.

• Java automatically creates the array and fills its elements with
the initialization values.
– row 0 {1, 2, 3}
– row 1 {4, 5, 6}
– row 2 {7, 8, 9}
• Declares an array with three rows and three columns.
The length Field
• Two-dimensional arrays are arrays of one-dimensional arrays.
• To access the length fields of two dimensional array:
• The length field of the array gives the number of rows in the array and
each row has a length constant telling how many columns are there in
that row. Each row can have a different number of columns.
Summing the Elements of a Two-Dimensional
Array

How do you sum the Rows or Columns of a Two-Dimensional Array?


Ragged Arrays
• When the rows of a two-dimensional array are of different
lengths, the array is known as a ragged array.
• You can create a ragged array by creating a two-dimensional
array with a specific number of rows, but no columns.

• Then create the individual rows.


More Than Two Dimensions

• Java does not limit the number of dimensions that an


array may be.
• More than three dimensions is hard to visualize, but can
be useful in some programming problems.
7.13 Command-Line Arguments (1 of 2)

• A Java program can receive arguments from the


operating system command-line.
• The main method has a header that looks like this:

• The main method receives a String array as a


parameter.
• The array that is passed into the args parameter comes
from the operating system command-line.
7.13 Command-Line Arguments (2 of 2)

• To run the example:

• Example: CommandLine.java
• It is not required that the name of main’s parameter array
be args.
Variable-Length Argument Lists

• Special type parameter – vararg…


– Vararg parameters are actually arrays
– Examples: VarArgsDemo1.java, VarargsDemo2.java

int result;
result = sum(10, 20);
result = sum(10, 20, 30, 40);
result = sum(10, 20, 30, 40, 50, 60);
//All will work fine.
7.14 The Arraylist Class

• Similar to an array, an ArrayList allows object storage


• Unlike an array, an ArrayList object:
– Automatically expands when a new item is added
– Automatically shrinks when items are removed
• Requires:
Creating an ArrayList

• This specifies that the ArrayList can hold String


objects.
• If we try to store any other type of object in this
ArrayList, an error will occur.
Using an ArrayList

• To populate the ArrayList, use the add method:



• To get the current size, call the size method



• To access items in an ArrayList, use the get method

In this statement 1 is the index of the item to get.


• Example: ArrayListDemo1.java
Using an ArrayList
• The ArrayList class's toString method returns a string
representing all items in the ArrayList

• This statement yields :

• The ArrayList class's remove method removes designated item


from the ArrayList

This statement removes the second item.


• See example: ArrayListDemo3.java
Using an ArrayList
• The ArrayList class's add method with one argument adds
new items to the end of the ArrayList
• To insert items at a location of choice, use the add method
with two arguments:

This statement inserts the String "Mary" at index 1


• To replace an existing item, use the set method:

This statement replaces “Mary” with “Becky”


• See example: ArrayListDemo5.java
Using an ArrayList

• An ArrayList has a capacity, which is the number of


items it can hold without increasing its size.
• The default capacity of an ArrayList is 10 items.
• To designate a different capacity, use a parameterized
constructor:
Using an ArrayList

• You can store any type of object in an ArrayList


Using an ArrayList

See: ArrayListDemo6.java
Using an ArrayList

• The diamond operator


– Beginning in Java 7, you can use the <> operator for
simpler ArrayList declarations:

Java infers the type of the ArrayList object from the


variable declaration.

You might also like