Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Lecture 5 - Array _ ArrayList

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lecture 5 - Array _ ArrayList

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Arrays & ArrayLists

(IT069IU)

Le Duy Tan, Ph.D.


📧 ldtan@hcmiu.edu.vn

🌐 leduytanit.com 1
Previously,
- Casting types.
- Control flow statements:
- Decision making statements:
- If
- If…else
- Switch
- Loop statements:
- While
- Do while
- For
- Jump statements:
- Break statement
- Continue statement
- Static Keyword
- Static Method
- Static Variable
- Overloading
- Method Overloading
- Constructor Overloading
- Final Keyword 2
- Constant Variable
Agenda
- Increment and Decrement Operators
- Scope of Declarations
- this keyword
- Array:
- Declare and Create Array
- Loop through Array
- Pass Arrays to Methods
- Pass by Value vs Pass by Reference
- Multidimensional Arrays
- Class Arrays for helper methods
- ArrayList (Collections Class)
- Array vs ArrayList

3
Increment and Decrement Operators
- Like C, Java has two unary operators:
- Increment operator ++
- Decrement operator --

4
- For example, the three assignment statements:

- can be written more concisely with compound assignment operators


as

- prefix increment operators as

- postfix increment operators as


6
Scope of Declaration

7
Scope of Declarations
- You’ve seen declarations of various Java entities, such as classes, methods,
variables and parameters.
- The scope of declaration refers to the places in the code that an entity is
accessible.
- There are generally three main “levels” of scope:
- If something has class scope, it means it is accessible across an entire class. For
examples:
- Variables (class variables, instance variables), Constants, and Methods.
- If something has method scope, it means it is accessible across an entire single method,
but not before the line on which it is declared. For example:
- Local variables are declared inside a method. (method variables)
- Parameters in method header
- If something has block scope or inner block scope, then it is accessible within just a
section of the block. These variables “go out of scope” at the end of the loop. For example:
- Initialized variables in a for loop header.
- Local variable declared inside while loop.
8
Simple Example of Scope
- In this method, the variable a has method scope, but the variable x has
block scope.
- The variable a can be used throughout the method, because it has method
scope.
- The variable x can be used within the loop itself, but not after the loop. It
won’t even compile. It has fallen out of scope.

9
Another Example of Scope
- Interestingly, we can reuse the same variable name (x) for a different
variable, and the two won’t conflict because both x variable only exists
within each loop.

10
Name Hiding
- When two variables are in different scopes and they have the same name.
- When this happens, the variable in the smaller scope “hides” the variable in the
larger scope. This is a situation called name hiding.
- One solution is to just always choose a different names for local variables and
parameters compared to the class-level instance variable.
- “this” is a special reference to the current instance that a method or constructor is
running in. It’s a quick and easy way to reach up into the class scope and work
with instance variables and even methods that belong to the class.
Choose same names but use this
Choose different names for parameters keyword to refer to class-level variables

11
[Question] Can you tell which variable
“hides” which variable and which scope?

12
Meme about Scope of Declaration

13
Array & ArrayList

14
Store multiple items of the same type
- Imagine you have a high score board in a game, with 10 high scores
on it. Using only the tools we know so far, you can create one variable
for every score you want to keep track of:

- What if you had 10,000 scores? Too many variable!!! 15


Array is here to save you!
- with 10 high scores, you want to keep track of:

16
Array
- An array is a group of variables (called elements or components)
containing values of the same type.
- Arrays are objects, so they’re considered reference types.

int[ ] x = new int[5];


x[0] = 34;
x[1] = 21;
x[2] = 2;
x[3] = 66;
x[4] = 567;
17
Array Declaration Syntax
- Array Declaration (array variable points to null):
data_type[] arrayName;
- Allocate actual memory for array members:
arrayName = new data_type[size];
- You can do both steps in one line:
data_type[] arrayName = new data_type[size];
For Example:
- you declare a new array with two steps:

- You can declare a new array of 12 integers in one step like this:
18
Array Initializer Example

19
Default Value for Array Element
- When an array is created, each of its elements receives a default value.
For example:
- zero for the numeric primitive-type elements
- false for boolean elements
- null for references

20
Readability for Array Declaration

- A program can create several arrays in a single declaration. The


following declaration reserves 100 elements for b and 27 elements for x:

- For readability, we prefer to declare only one variable at a time:

21
Array Initializer

- You can create an array and initialize its elements with an array
initializer.
- An array initializer is a comma-separated list of expressions (called an
initializer list) enclosed in braces.

22
Access Element in Array using Index

int[ ] c = {-45, 6, 0, 72, 1543, -89, 0, 62, -3, 1, 6453, 78}

int a =5, b = 6;

c[a+b] +=2;

What will be changed in the array?

int sum = c[0] + c[1] + c[2];

What is the output of sum? 23


Array Length Usefulness
Output:

24
Loop Through 1-Dimensional Array
- Use for loop:
The Same Output:

- Use enhanced for loop:

[Question] What is the


advantage and disadvantage of
for loop and enhanced for loop
to loop through array?
25
Initialize Array Example
InitArray.java

26
Array Initializer Example
InitArray.java

27
Sum Array Example

28
Enhanced for Statement
- The enhanced for statement iterates through the elements of an array
without using a counter, thus avoiding the possibility of “stepping outside”
the array.
- where parameter has a type and an identifier (e.g., int number), and
arrayName is the array through which to iterate.

- Instead, using counter in a for loop to loop through an array:

- We can just use:


29
Enhanced For Loop Example

30
Pass Arrays to Methods
- You can pass an array to a method just like you pass a variable to a method.

For example:

- If array hourlyTemperatures is declared as:

- The method call can be:

- Method header might be written as:

31
Output:

[Question] Why do we use an


enhanced loop for
calculateAverage method and a
normal loop for
convertToFahrenheit method?

32
Pass-By-Value vs. Pass-By-Reference

[Question] Which
example passes by
value to a method
or which passes by
reference to a
method?

33
Let’s revisited: Variable
- Remember, a variable is a place in memory where you can store
information.
- It’s like a little box or bucket to put stuff in.
- Each variable has a name and a type.
- For primitive data type:
- The value of a variable stores the actual value of the data.
- For reference data type:
- The value of a variable stores the memory address (reference) to the
location of the data. Similar to pointer address in C.

34
Primitive Data Type

- For primitive data type:


- The value of a variable stores the actual value of the data.

35
Primitive Data Type

36
Array is a Reference Data Type
- For reference data type:
- The value of a variable stores the memory address (reference) to the
location of the data. Similar to pointer address in C.

37
Compared This
[Question] Can you guess
what is the output for each
case?

38
[Question] Why the modifyArray
method change the original array
but modifyElement method does not
change the value of the original
element of the array? 39
The Nature of Multidimensional Array
- Two dimensional array is one type of multidimensional array.

1-Dimensional Array 2-Dimensional Array 3-Dimensional Array

40
Multidimensional Arrays
- Multidimensional arrays with two dimensions are often used to represent
tables of values with data arranged in rows and columns.
- To identify a particular table element, you specify two indices.
- By convention, the first identifies the element’s row and the second its
column.

41
2-Dimensional Array Declaration Syntax

- Array Declaration (array variable points to null):


data_type[][] arrayName;
- Allocate actual memory for array members:
arrayName = new data_type[size][size];
- You can do both steps in one line:
data_type[][] arrayName = new data_type[size][size];
For Example:
- you declare a new array with two steps:

- You can declare a new 2-dimensional array of in one step like this:
42
Creating Two-Dimensional Arrays with Array-
Creation Expressions
- Here is to declare array b and assign it a reference to a three-by-four array:

- A multidimensional array in which each row has a different number of


columns can be created as follows:

43
Default Values of 2-Dimensional Array
- Like the same rule with one dimensional array, each of its elements
receives a default value. For example:
- zero for the numeric primitive-type elements
- false for boolean elements
- null for references

44
Multiple Dimension Array Index
- Row index usually starts from top to bottom, starting with 0.
- Column index usually starts from left to right, starting with 0.
- To access each element in the array, we need to specific:

arrayName[row index, column index]

45
Nested Array Initializers
- Like one-dimensional arrays, multidimensional arrays can be
initialized with array initializers in declarations.
int[ ][ ] myArray = { {8,6,7}, {9,9,8}, {6,8,10}, {7,9,5} };

46
Nested Array Initializers
- In fact, the lengths of the rows in array b are not required to be the
same:

int[ ][ ] myArray = { {1, 2}, {3, 4, 5} };

47
Two-Dimensional Array Length

48
Loop through 2-dimensional array
- Use for loop: The Same Output:

[Question] What is the


advantage and disadvantage of
for loop and enhanced for loop
- Use for each loop: to loop through array?

49
Pass 2-Dimensional Array to a Method

Output:

50
Variable-Length Argument Lists
- With variable-length argument lists, you can create methods that receive an
unspecified number of arguments.
- A type followed by an ellipsis (...) in a method’s parameter list indicates that
the method receives a variable number of arguments of that particular type.
- This use of the ellipsis can occur only once in a parameter list, and the
ellipsis, together with its type and the parameter name, must be placed at the
end of the parameter list.
- Method header look like:

- Method call now can take any number of parameters:

51
Variable-Length Argument Lists Example
Output:

52
Variable-Length Argument with Other Arguments Example

[Question] Can you guess what is the


output and explain why is that? 53
Using Command-Line Arguments
public static void main(String[] args)
- Remember, we have:
- When an application is executed using the java command, Java
passes the command-line arguments that appear after the class
name in the java command to the application’s main method as
Strings in the array args.
- The number of command-line arguments is obtained by accessing
the array’s length attribute. Common uses of commandline
arguments include passing options and filenames to applications
- The command passes three arguments, 5, 0 and 4, to the application
InitArray.

54
Using Command-Line Arguments Example
If you try to execute without command-
line arguments:

For this program, you need to execute with


command-line arguments:

55
Class Arrays - Helper Methods for Arrays
- Class Arrays helps you avoid reinventing the wheel by providing static
methods for common array manipulations.
- These methods include sort for sorting an array, binarySearch for searching
an element in a sorted array, equals for comparing arrays and fill for placing
values into an array.
- These methods are overloaded for primitive-type arrays and for arrays of
objects.

56
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
Class Arrays Example

Output:

[Question] Can you find out which


method in Arrays Class we use in
this program?

57
Output:

[Question] Can you find out which


method in Arrays Class we use in
this program?

58
Limitation of Array in Java
- Just like C, the size of an array can't be changed.
- The dimension of an array is determined the moment the array is created, and cannot be
changed later on.
- If you want a bigger array you have to instantiate a new one, and copy elements from the
old array to the new one. (Like in the below code)
- The array occupies an amount of memory that is proportional to its size, independently of
the number of elements that are actually there.
- If we want to keep the elements of the collection ordered, and insert a new value in its correct
position, or remove it, then, for each such operation we may need to move many elements.
this is very inefficient.
Extend array by two more elements (inconvenient way):

Output:
59
Collections
& Class ArrayList
Resizable Collections

60
ArrayList
- The Java API provides several predefined data structures, called
collections, used to store groups of related objects.
- ArrayList is a resizable array implementation in java. ArrayList grows
dynamically and ensures that there is always a space to add elements.
- The collection class ArrayList<T> (package java.util) provides a
convenient solution to this problem—it can dynamically change its size
to accommodate more elements. The T (by convention) is a placeholder.

ArrayList to store String elements:

ArrayList to store Integer elements:


61
ArrayList Methods

62
ArrayList & Array Example
Output:

63
ArrayList Example Output:

64
Output:

65
Array [ ] vs ArrayList < >
- Array cannot change the length of array once created while ArrayList can
grow to meet the demand.
- We cannot store primitives in ArrayList, it can only store objects. But
array can contain both primitives and objects in Java. So you need to use
alternative reference data type for primitive data types. (int -> Integer)
- Array is faster for reading and processing than ArrayList.

66
https://stackoverflow.com/questions/716597/array-or-list-in-java-which-is-faster
Which situation below need array or arrayList?
- A ticket in the 649 game with 6 numbers?
- A 3-dice game? Such as, tài xỉu.
- A classroom with a list of students like Edusoft system?
- An ecommerce order with any amount of items like on Shopee.
- Can you think of other examples?

67
Recap
- Increment and Decrement Operators
- Scope of Declarations
- this keyword
- Array:
- Declare and Create Array
- Loop through Array
- Pass Arrays to Methods
- Pass by Value vs Pass by Reference
- Multidimensional Arrays
- Class Arrays for helper methods
- ArrayList (Collections Class)
- Array vs ArrayList

68
Java Developer Productivity Survey 2022

To get you started with labs this week

69
https://www.jrebel.com/resources/java-developer-productivity-report-2022
70
71
72
73
74
75
76
77
78
Stack Overflow Developer Survey 2021

https://insights.stackoverflow.com/survey/2021#experience-learn-code

79
What do you do when you get stuck?

80
Popular Tools

81
Thank you for your listening!

82

You might also like