0% found this document useful (0 votes)
1 views20 pages

Tutorial 5 Array

The document provides an overview of arrays and ArrayLists in Java, detailing how to declare, initialize, and manipulate them. It explains the concept of bounds checking, the use of two-dimensional arrays, and the differences between arrays and ArrayLists, including their respective methods for adding and removing elements. Additionally, it highlights the efficiency of ArrayLists in terms of element insertion and removal.

Uploaded by

Mobile 3G
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)
1 views20 pages

Tutorial 5 Array

The document provides an overview of arrays and ArrayLists in Java, detailing how to declare, initialize, and manipulate them. It explains the concept of bounds checking, the use of two-dimensional arrays, and the differences between arrays and ArrayLists, including their respective methods for adding and removing elements. Additionally, it highlights the efficiency of ArrayLists in terms of element insertion and removal.

Uploaded by

Mobile 3G
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

5.

Arrays and
ArrayList

Following slides are


borrowed from the
book’s free supplement
Presentation Slides,
[Link]
Arrays
• The values held in an array are called
array elements
• An array stores multiple values of the
same type – the element type
• The element type can be a primitive type
or an object reference
• Therefore, we can create an array of
integers, an array of characters, an array
of String objects, an array of Coin objects,
etc.
• In Java, the array itself is an object that
must be instantiated
© 2004 Pearson Addison-Wesley. All rights reserved 1-2
Declaring Arrays
• The scores array could be declared as
follows:
scores 79
int[] scores = new int[10]; 87
94
• The type of the variable scores is int[]
(an array of integers) 82
67
• Note that the array type does not specify
98
its size, but each object of that type has
a specific size 87
81
• The reference variable scores is set to a
74
new array object that can hold 10
integers 91

© 2004 Pearson Addison-Wesley. All rights reserved 1-3


Using Arrays
• The iterator version of the for loop can be
used when processing array elements

for (int score : scores)


[Link] (score);

• This is only appropriate when processing all


array elements from top (lowest index) to
bottom (highest index)

• Each array object has a public constant called


length that stores the size of the array. Note
that length holds the number of elements, not
the largest index

© 2004 Pearson Addison-Wesley. All rights reserved 1-4


Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must
specify a valid element. That is, the index
value must be in range 0 to N-1
• The Java interpreter throws an
ArrayIndexOutOfBoundsException if an
array index is out of bounds (called
automatic bounds checking)

• It’s common to introduce off-by-one errors


when using arrays problem
int[] scores = new int[10];
for (int index=0; index <= 100; index++)
codes[index] = index*50 + epsilon;
© 2004 Pearson Addison-Wesley. All rights reserved 1-5
Example: [Link]

double[] numbers = new double[10];


for (int index = 0; index < [Link]; index++) {
[Link] ("Enter number " + (index+1) + ": ");
numbers[index] = [Link]();
}
[Link] ("The numbers in reverse order:");
for (int index = [Link]-1; index >= 0; index--)
[Link] (numbers[index] + " ");
}

There is a shortcut link in


[Link]
© 2004 Pearson Addison-Wesley. All rights reserved 1-6
Example: [Link]
• Length of a String line is [Link](),
where array upper[] is [Link]. The
difference means ??

• What’s this upper[current-'A']++; and


lower[current-'a']++;

• Q: the # of appearance of letter ‘B’, ‘c’ are


stored in where? upper[x] or lower[y]?

• Q: what’s the result for string ‘aBcD’ ?

There is a shortcut link in


[Link]
© 2004 Pearson Addison-Wesley. All rights reserved 1-7
Initializer Lists
• An initializer list can be used to instantiate and fill
an array in one step. But it can be used only in the
array declaration
• The values are delimited by braces and separated
by commas
• Note that when an initializer list is used:
 the new operator is not used
 no size value is specified, (size is determined by the
number of items in the initializer list)

• Examples:
int[] units = {147, 323, 89, 933, 540};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

© 2004 Pearson Addison-Wesley. All rights reserved 1-8


Arrays of Objects
• The elements of an array can be object references

• The following declaration reserves space to store 5


references to String objects

String[] words = new String[5];

• It does NOT create the String objects themselves

• Initially an array of objects holds null references

• Each object stored in an array must be instantiated


separately

• Another way to declare a string: String[] words =


{"friendship", "loyalty", "honor", null,null};

© 2004 Pearson Addison-Wesley. All rights reserved 1-9


Arrays of Objects
• The words array words -
when initially -
declared: -
-
• After some String objects
-
are created and stored in
the array:
words[0]=“friendship”; …

words “friendship
”“loyalty”

“honor”
-
-

© 2004 Pearson Addison-Wesley. All rights reserved 1-10


Arrays as Parameters
• An entire array can be passed as a
parameter to a method

• Like any other object, the reference to the


array is passed, making the formal and
actual parameters aliases of each other

• Therefore, changing an array element


within the method changes the original

• An individual array element can be passed


to a method as well, in which case the
type of the formal parameter is the same
as the element type
© 2004 Pearson Addison-Wesley. All rights reserved 1-11
Two-Dimensional Arrays
• A one-dimensional array stores a list of elements

• A two-dimensional array can be thought of as a


table of elements, with rows and columns

one two
dimension dimensions

© 2004 Pearson Addison-Wesley. All rights reserved 1-12


Two-Dimensional Arrays
• A one-dimensional array stores a list of elements
• A two-dimensional array can be thought of as a
table of elements, with rows and columns

int [][] nums = new int[5][4];

© 2004 Pearson Addison-Wesley. All rights reserved 1-13


Two-Dimensional Arrays
• A two-dimensional array can be thought of as a
table of elements, with rows and columns
int [][] nums = new int[5][];
int[] a0 = {2,8,1,6,3,1,5}; nums[0] = a0;
int[] a1 = {1,6,5}; nums[1] = a1;

© 2004 Pearson Addison-Wesley. All rights reserved 1-14


Two-Dimensional Arrays
• To be precise, in Java a two-dimensional
array is an array of arrays
• A two-dimensional array is declared by
specifying the size of each dimension
separately:
int[][] scores = new int[12][50];
• A array element is referenced using two
index values:
value = scores[3][6]
• The array stored in one row can be
specified using one index: scores[3]
© 2004 Pearson Addison-Wesley. All rights reserved 1-15
Two-Dimensional Arrays
int[][] table = new int[5][12];

Expression Type Description


table int[][] 2D array of integers, or
array of integer arrays

table[5] int[] array of integers


table[5][12] int integer

• Example: [Link]

© 2004 Pearson Addison-Wesley. All rights reserved 1-16


Multidimensional Arrays
• An array can have many dimensions – if it
has more than one dimension, it is called a
multidimensional array
• Each dimension subdivides the previous
one into the specified number of elements
• Each dimension has its own length
constant
• Because each dimension is an array of
array references, the arrays within one
dimension can be of different lengths
 these are sometimes called ragged arrays

© 2004 Pearson Addison-Wesley. All rights reserved 1-17


ArrayList Class: [Link]
• An ArrayList object like an array, it can
store a list object references,
• Declaration: ArrayList<String> band = new
ArrayList<String>();
 An ArrayList that stores String objects.

• Get element by a index: [Link](1)


• However, you cannot use the bracket
syntax with an ArrayList object: band[1]
• An ArrayList object grows and shrinks as
needed, to check its size: [Link](),
[Link]()

© 2004 Pearson Addison-Wesley. All rights reserved 1-18


ArrayList Class: [Link]
• Declaration: ArrayList<String> band = new
ArrayList<String>();

• Elements can be inserted or removed by


calling methods:
 [Link] ("Paul");
 int location = [Link] ("Paul");
[Link] (location);
 boolean success = [Link] ("Paul");

• Output all elements:


 for (String str : band)
[Link] (str);

© 2004 Pearson Addison-Wesley. All rights reserved 1-19


ArrayList Efficiency
• The ArrayList class is implemented using an
underlying array

• When an element is inserted, the other elements


"move aside" to make room. Likewise, when an
element is removed, the list "collapses" to close
the gap

• The array is manipulated so that indexes remain


continuous as elements are added or removed

• If elements are added to and removed from the


end of the list, this processing is fairly efficient

• But as elements are inserted and removed from the


front or middle of the list, the remaining elements
are shifted

© 2004 Pearson Addison-Wesley. All rights reserved 1-20

You might also like