SlideShare a Scribd company logo
1 of 19
Programming in Java
5-day workshop
Data Structures
Matt Collison
JP Morgan Chase 2021
PiJ3.3: Data Structures
Arrays
• In Java, an array is an object which contains a collection of similar type
elements that have contiguous memory location.
• The index is always an integer. First index is 0, last index is
arrayName.length-1.
Note: length is a final attribute of an array
Creating an array object
• The same as normal objects, creating an array object also includes
three steps:
1. Declaration
String[] names;
2. Instantiation
names = new String[2];
3. Initialization
names[0] = "Alex";
names[1] = "Oliver";
Creating an array object
• Alternatively, we could also use only one statements:
String[] names = {"Alex", "Oliver"};
• Or use two statements:
String[] names;
names = new String[]{"Alex", "Oliver"};
Creating and using an array object
// A demo of creating and using array objects
public class ArrayApp{
public static void main(String[] args) {
// one statement for creating an array
String[] strs = {"ANDROID", "JSP", "JAVA", "STRUTS"};
for ( int i=0; i < strs.length; i++ ) {
System.out.println( strs[i] )
}
int[] numbers;
numbers = new int[]{8,10,3,50};
for (int num: numbers) { System.out.println(num);
}
}
Populating an array
// three statements for creating an array
Rectangle[] rects;
rects = new Rectangle[2];
rects[0] = new Rectangle(10,5);
rects[1] = new Rectangle();
for( Rectangle rt: rects ) {
System.out.println( rt.getArea() );
}
• Exercise: Use only one statement to replace the above code for creating an
array of 2 rectangle objects.
Rectangle rects[]={new Rectangle(10,5), new Rectangle()};
Multi-dimensional Array
Rectangular array:
• int[][] matrix = new int[7][5]; // 7 rows, 5 columns Arbitrary sizes:
• int[][] matrix = {{3,4,5},{10}, {-7,-9}}
Incrementally constructed arrays:
• int[][] matrix = new int[3][];
• matrix[0] = new int[]{3,4,5};
• matrix[1] = new int[1];
• matrix[2] = new int[]{-7,-9};
Accessing the array:
• int a = matrix[2][1];
ArrayList vs arrays
• Any array object is fix-length.
Q: What about if:
• we don’t know in advance the number of elements?
• we would like to dynamically add or remove some elements in an
array?
• A: Use ArrayList class
import java.util.ArrayList;
ArrayList
Creating an ArrayList of String objects:
ArrayList<String> names = new ArrayList<String>();
Or:
ArrayList<String> names = new ArrayList<>();//Java SE 7 onwards
• ArrayList<E> is a generic class: E could be any class type (not primitive).
• ArrayList<Rectangle>
• ArrayList<Book>
• ArrayList<Float>
• ...
• NOTE: A generic class is a class that require a type parameter.
ArrayList methods
Adding objects:
• names.add("Alex");
Get the length:
• int n = names.size();
Read the i-th element:
• String name = names.get(i);
Remove the i-th element:
• names.remove(i);
• Full lists: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
• Q: How would you get the length of an equivalent array?
Example: Use an ArrayList object to store the
two rectangles:
Rectangle[] rects = { new Rectangle(10,5), new Rectangle() };
import java.util.ArrayList;
public class ArrayRectangleApp {
public static void main(String[] args){
// declare an ArrayList of Rectangle objects
ArrayList<Rectangle> rectangles = new ArrayList<>();
// dynamically add Rectangle objects
rectangles.add(new Rectangle(10,5));
rectangles.add(new Rectangle());
for (int i=0;i<rectangles.size();i++){
System.out.println( i + " area: ” + rectangles.get(i).getArea() );
}
}
}
Feature table: Array vs ArrayList
Array ArrayList
Size Fixed Adjustable
Contains Primitives and objects Objects only
Get size .length .size()
Get item [ index ] .get( index )
Dimensions Multidimensional One-dimensional *
Implements None Collections
Word frequency exercise
Q: Write a program to count the number of times that each unique word occurs in dracula.txt
ArrayList<String> words = new ArrayList<>();
ArrayList<Integer> counts = new ArrayList<>();
for( String word : readFile() ) {
//complete the logic
if( words.contains(word) ){
int index = words.indexOf(word);
counts[index] += 1;
} else {
words.add(word);
count.add(1);
}
}
• Wouldn’t it be useful to be able to map directly between the values in the lists. That is what a HashMap does.
HashMap as a key-value store
HashMap<String,Integer> wordFreq = new HashMap<>();
for( String word : readFile() ) {
if( wordFreq.containsKey(word) ){
wordFreq.get(word) += 1;
} else {
wordFreq.put(word, 1);
}
}
Access values with .get( key )
Insert values with .put( key )
HashMaps
• HashMaps are key-value stores that link a set of ‘keys’ directly to the
value.
• Performance is far better for data retrieval due to reduced complexity
• They are imported from:
import java.util.HashMap;
• Syntax uses generics:
HashMap<K, V> identifier = new HashMap<>();
Learning resources
The workshop homepage
https://mcollison.github.io/JPMC-java-intro-2021/
The course materials
https://mcollison.github.io/java-programming-foundations/
• Session worksheets – updated each week
Additional resources
• Think Java: How to think like a computer scientist
• Allen B Downey (O’Reilly Press)
• Available under Creative Commons license
• https://greenteapress.com/wp/think-java-2e/
• Oracle central Java Documentation –
https://docs.oracle.com/javase/8/docs/api/
• Other sources:
• W3Schools Java - https://www.w3schools.com/java/
• stack overflow - https://stackoverflow.com/
• Coding bat - https://codingbat.com/java

More Related Content

What's hot

Collections generic
Collections genericCollections generic
Collections genericsandhish
 
Array in Java
Array in JavaArray in Java
Array in JavaAli shah
 
Week06
Week06Week06
Week06hccit
 
2nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 12nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 1Aahwini Esware gowda
 
Python list 28_10_2020
Python list 28_10_2020Python list 28_10_2020
Python list 28_10_2020Sugnan M
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 dnikhilarora2211
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its typesNavtar Sidhu Brar
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 

What's hot (20)

Collections generic
Collections genericCollections generic
Collections generic
 
Arrays
ArraysArrays
Arrays
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Week06
Week06Week06
Week06
 
2nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 12nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 1
 
Data structures
Data structuresData structures
Data structures
 
Python list 28_10_2020
Python list 28_10_2020Python list 28_10_2020
Python list 28_10_2020
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 d
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
 
Java arrays
Java arraysJava arrays
Java arrays
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 

Similar to Pi j3.4 data-structures

Similar to Pi j3.4 data-structures (20)

arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Java 103
Java 103Java 103
Java 103
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
Arrays are used to store multiple values in a single variable, instead of dec...
Arrays are used to store multiple values in a single variable, instead of dec...Arrays are used to store multiple values in a single variable, instead of dec...
Arrays are used to store multiple values in a single variable, instead of dec...
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 

More from mcollison

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packagesmcollison
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classesmcollison
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introductionmcollison
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loopsmcollison
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operatorsmcollison
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignmentmcollison
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-javamcollison
 

More from mcollison (11)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Pi j2.2 classes
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
 
Pi j1.4 loops
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loops
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Pi j1.1 what-is-java
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-java
 

Recently uploaded

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 

Recently uploaded (20)

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 

Pi j3.4 data-structures

  • 1. Programming in Java 5-day workshop Data Structures Matt Collison JP Morgan Chase 2021 PiJ3.3: Data Structures
  • 2. Arrays • In Java, an array is an object which contains a collection of similar type elements that have contiguous memory location. • The index is always an integer. First index is 0, last index is arrayName.length-1. Note: length is a final attribute of an array
  • 3. Creating an array object • The same as normal objects, creating an array object also includes three steps: 1. Declaration String[] names; 2. Instantiation names = new String[2]; 3. Initialization names[0] = "Alex"; names[1] = "Oliver";
  • 4. Creating an array object • Alternatively, we could also use only one statements: String[] names = {"Alex", "Oliver"}; • Or use two statements: String[] names; names = new String[]{"Alex", "Oliver"};
  • 5. Creating and using an array object // A demo of creating and using array objects public class ArrayApp{ public static void main(String[] args) { // one statement for creating an array String[] strs = {"ANDROID", "JSP", "JAVA", "STRUTS"}; for ( int i=0; i < strs.length; i++ ) { System.out.println( strs[i] ) } int[] numbers; numbers = new int[]{8,10,3,50}; for (int num: numbers) { System.out.println(num); } }
  • 6. Populating an array // three statements for creating an array Rectangle[] rects; rects = new Rectangle[2]; rects[0] = new Rectangle(10,5); rects[1] = new Rectangle(); for( Rectangle rt: rects ) { System.out.println( rt.getArea() ); } • Exercise: Use only one statement to replace the above code for creating an array of 2 rectangle objects. Rectangle rects[]={new Rectangle(10,5), new Rectangle()};
  • 7. Multi-dimensional Array Rectangular array: • int[][] matrix = new int[7][5]; // 7 rows, 5 columns Arbitrary sizes: • int[][] matrix = {{3,4,5},{10}, {-7,-9}} Incrementally constructed arrays: • int[][] matrix = new int[3][]; • matrix[0] = new int[]{3,4,5}; • matrix[1] = new int[1]; • matrix[2] = new int[]{-7,-9}; Accessing the array: • int a = matrix[2][1];
  • 8. ArrayList vs arrays • Any array object is fix-length. Q: What about if: • we don’t know in advance the number of elements? • we would like to dynamically add or remove some elements in an array? • A: Use ArrayList class import java.util.ArrayList;
  • 9. ArrayList Creating an ArrayList of String objects: ArrayList<String> names = new ArrayList<String>(); Or: ArrayList<String> names = new ArrayList<>();//Java SE 7 onwards • ArrayList<E> is a generic class: E could be any class type (not primitive). • ArrayList<Rectangle> • ArrayList<Book> • ArrayList<Float> • ... • NOTE: A generic class is a class that require a type parameter.
  • 10. ArrayList methods Adding objects: • names.add("Alex"); Get the length: • int n = names.size(); Read the i-th element: • String name = names.get(i); Remove the i-th element: • names.remove(i); • Full lists: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html • Q: How would you get the length of an equivalent array?
  • 11. Example: Use an ArrayList object to store the two rectangles: Rectangle[] rects = { new Rectangle(10,5), new Rectangle() }; import java.util.ArrayList; public class ArrayRectangleApp { public static void main(String[] args){ // declare an ArrayList of Rectangle objects ArrayList<Rectangle> rectangles = new ArrayList<>(); // dynamically add Rectangle objects rectangles.add(new Rectangle(10,5)); rectangles.add(new Rectangle()); for (int i=0;i<rectangles.size();i++){ System.out.println( i + " area: ” + rectangles.get(i).getArea() ); } } }
  • 12. Feature table: Array vs ArrayList Array ArrayList Size Fixed Adjustable Contains Primitives and objects Objects only Get size .length .size() Get item [ index ] .get( index ) Dimensions Multidimensional One-dimensional * Implements None Collections
  • 13.
  • 14.
  • 15. Word frequency exercise Q: Write a program to count the number of times that each unique word occurs in dracula.txt ArrayList<String> words = new ArrayList<>(); ArrayList<Integer> counts = new ArrayList<>(); for( String word : readFile() ) { //complete the logic if( words.contains(word) ){ int index = words.indexOf(word); counts[index] += 1; } else { words.add(word); count.add(1); } } • Wouldn’t it be useful to be able to map directly between the values in the lists. That is what a HashMap does.
  • 16. HashMap as a key-value store HashMap<String,Integer> wordFreq = new HashMap<>(); for( String word : readFile() ) { if( wordFreq.containsKey(word) ){ wordFreq.get(word) += 1; } else { wordFreq.put(word, 1); } } Access values with .get( key ) Insert values with .put( key )
  • 17. HashMaps • HashMaps are key-value stores that link a set of ‘keys’ directly to the value. • Performance is far better for data retrieval due to reduced complexity • They are imported from: import java.util.HashMap; • Syntax uses generics: HashMap<K, V> identifier = new HashMap<>();
  • 18. Learning resources The workshop homepage https://mcollison.github.io/JPMC-java-intro-2021/ The course materials https://mcollison.github.io/java-programming-foundations/ • Session worksheets – updated each week
  • 19. Additional resources • Think Java: How to think like a computer scientist • Allen B Downey (O’Reilly Press) • Available under Creative Commons license • https://greenteapress.com/wp/think-java-2e/ • Oracle central Java Documentation – https://docs.oracle.com/javase/8/docs/api/ • Other sources: • W3Schools Java - https://www.w3schools.com/java/ • stack overflow - https://stackoverflow.com/ • Coding bat - https://codingbat.com/java