SlideShare a Scribd company logo
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
Pi j3.4 data-structures
Pi j3.4 data-structures
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 (20)

DOCX
Collections generic
sandhish
 
PPT
Arrays
SARITHA REDDY
 
PDF
Array in Java
Ali shah
 
PDF
Week06
hccit
 
PDF
2nd puc computer science chapter 3 data structures 1
Aahwini Esware gowda
 
PPTX
Data structures
Pranav Gupta
 
PPT
Python list 28_10_2020
Sugnan M
 
PDF
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
PDF
Arrays in python
moazamali28
 
PDF
9 python data structure-2
Prof. Dr. K. Adisesha
 
PDF
LectureNotes-06-DSA
Haitham El-Ghareeb
 
PDF
Java arrays (1)
Liza Abello
 
PPTX
Data structures in c#
SivaSankar Gorantla
 
PPTX
Row major and column major in 2 d
nikhilarora2211
 
PPTX
Data structure and its types
Navtar Sidhu Brar
 
PPT
Java arrays
Maneesha Caldera
 
PDF
LectureNotes-03-DSA
Haitham El-Ghareeb
 
PPT
Array in Java
Shehrevar Davierwala
 
PPTX
Array in C# 3.5
Gopal Ji Singh
 
PPTX
Java 103 intro to java data structures
agorolabs
 
Collections generic
sandhish
 
Array in Java
Ali shah
 
Week06
hccit
 
2nd puc computer science chapter 3 data structures 1
Aahwini Esware gowda
 
Data structures
Pranav Gupta
 
Python list 28_10_2020
Sugnan M
 
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Arrays in python
moazamali28
 
9 python data structure-2
Prof. Dr. K. Adisesha
 
LectureNotes-06-DSA
Haitham El-Ghareeb
 
Java arrays (1)
Liza Abello
 
Data structures in c#
SivaSankar Gorantla
 
Row major and column major in 2 d
nikhilarora2211
 
Data structure and its types
Navtar Sidhu Brar
 
Java arrays
Maneesha Caldera
 
LectureNotes-03-DSA
Haitham El-Ghareeb
 
Array in Java
Shehrevar Davierwala
 
Array in C# 3.5
Gopal Ji Singh
 
Java 103 intro to java data structures
agorolabs
 

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

PPTX
Java 103
Manuela Grindei
 
PPTX
Arrays and Strings engineering education
csangani1
 
PPTX
java UNIkjvnjfkdnvkjdsnvjkdfsncvjksdnvkjfdnT 4.pptx
hofon47654
 
PPTX
javaArrays.pptx
AshishNayyar11
 
PDF
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
PPTX
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
DOCX
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PPTX
Java Programming
Nanthini Kempaiyan
 
PDF
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PPTX
Chapter6 (4) (1).pptx plog fix down more
mohammadalali41
 
PDF
Array
Ravi_Kant_Sahu
 
PPTX
6 arrays injava
irdginfo
 
PPTX
Tophcjdjjdjsjssjjdkdkdkfkfkdfkdic-2.pptx
akoboty11
 
PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PPT
Arrays in JAVA.ppt
SeethaDinesh
 
PPT
ch11.ppt
kavitamittal18
 
PPT
Arrays in java programming language slides
ssuser5d6130
 
PPTX
Arrays in java.pptx
Nagaraju Pamarthi
 
PPTX
Arrays in programming
TaseerRao
 
PDF
Aj unit2 notesjavadatastructures
Arthik Daniel
 
Java 103
Manuela Grindei
 
Arrays and Strings engineering education
csangani1
 
java UNIkjvnjfkdnvkjdsnvjkdfsncvjksdnvkjfdnT 4.pptx
hofon47654
 
javaArrays.pptx
AshishNayyar11
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Java Programming
Nanthini Kempaiyan
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Chapter6 (4) (1).pptx plog fix down more
mohammadalali41
 
6 arrays injava
irdginfo
 
Tophcjdjjdjsjssjjdkdkdkfkfkdfkdic-2.pptx
akoboty11
 
07. Java Array, Set and Maps
Intro C# Book
 
Arrays in JAVA.ppt
SeethaDinesh
 
ch11.ppt
kavitamittal18
 
Arrays in java programming language slides
ssuser5d6130
 
Arrays in java.pptx
Nagaraju Pamarthi
 
Arrays in programming
TaseerRao
 
Aj unit2 notesjavadatastructures
Arthik Daniel
 
Ad

More from mcollison (11)

PPTX
Pi j4.2 software-reliability
mcollison
 
PPTX
Pi j4.1 packages
mcollison
 
PPTX
Pi j3.1 inheritance
mcollison
 
PPTX
Pi j3.2 polymorphism
mcollison
 
PPTX
Pi j2.3 objects
mcollison
 
PPTX
Pi j2.2 classes
mcollison
 
PPTX
Pi j1.0 workshop-introduction
mcollison
 
PPTX
Pi j1.4 loops
mcollison
 
PPTX
Pi j1.3 operators
mcollison
 
PPTX
Pi j1.2 variable-assignment
mcollison
 
PPTX
Pi j1.1 what-is-java
mcollison
 
Pi j4.2 software-reliability
mcollison
 
Pi j4.1 packages
mcollison
 
Pi j3.1 inheritance
mcollison
 
Pi j3.2 polymorphism
mcollison
 
Pi j2.3 objects
mcollison
 
Pi j2.2 classes
mcollison
 
Pi j1.0 workshop-introduction
mcollison
 
Pi j1.4 loops
mcollison
 
Pi j1.3 operators
mcollison
 
Pi j1.2 variable-assignment
mcollison
 
Pi j1.1 what-is-java
mcollison
 
Ad

Recently uploaded (20)

PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
grade 5 lesson ENGLISH 5_Q1_PPT_WEEK3.pptx
SireQuinn
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
grade 5 lesson ENGLISH 5_Q1_PPT_WEEK3.pptx
SireQuinn
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 

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
  • 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