Lecture 5 - Array _ ArrayList
Lecture 5 - Array _ ArrayList
International University
School of Computer Science and Engineering
(IT069IU)
🌐 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:
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:
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.
- 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
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 a =5, b = 6;
c[a+b] +=2;
24
Loop Through 1-Dimensional Array
- Use for loop:
The Same Output:
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.
30
Pass Arrays to Methods
- You can pass an array to a method just like you pass a variable to a method.
For example:
31
Output:
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
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.
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
- 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:
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:
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:
47
Two-Dimensional Array Length
48
Loop through 2-dimensional array
- Use for loop: The Same Output:
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:
51
Variable-Length Argument Lists Example
Output:
52
Variable-Length Argument with Other Arguments Example
54
Using Command-Line Arguments Example
If you try to execute without 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:
57
Output:
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.
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
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