Pi j3.4 data-structures

M
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
1 von 19

Recomendados

Lecture 6 - Arrays von
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - ArraysSyed Afaq Shah MACS CP
60 views28 Folien
Arrays Java von
Arrays JavaArrays Java
Arrays JavaJose Sumba
304 views4 Folien
An Introduction to Programming in Java: Arrays von
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysMartin Chapman
1.4K views59 Folien
Set data structure von
Set data structure Set data structure
Set data structure Tech_MX
24.8K views32 Folien
Java arrays von
Java arraysJava arrays
Java arraysJin Castor
1.4K views19 Folien

Más contenido relacionado

Was ist angesagt?

Collections generic von
Collections genericCollections generic
Collections genericsandhish
167 views9 Folien
Arrays von
ArraysArrays
ArraysSARITHA REDDY
26.2K views50 Folien
Array in Java von
Array in JavaArray in Java
Array in JavaAli shah
485 views12 Folien
Week06 von
Week06Week06
Week06hccit
324 views29 Folien
2nd puc computer science chapter 3 data structures 1 von
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
1.3K views19 Folien
Data structures von
Data structuresData structures
Data structuresPranav Gupta
1.4K views52 Folien

Was ist angesagt?(20)

Collections generic von sandhish
Collections genericCollections generic
Collections generic
sandhish167 views
Array in Java von Ali shah
Array in JavaArray in Java
Array in Java
Ali shah485 views
Week06 von hccit
Week06Week06
Week06
hccit324 views
2nd puc computer science chapter 3 data structures 1 von Aahwini Esware gowda
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
Python list 28_10_2020 von Sugnan M
Python list 28_10_2020Python list 28_10_2020
Python list 28_10_2020
Sugnan M15 views
Arrays In Python | Python Array Operations | Edureka von Edureka!
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!3.6K views
Arrays in python von moazamali28
Arrays in pythonArrays in python
Arrays in python
moazamali283.3K views
Row major and column major in 2 d von nikhilarora2211
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 d
nikhilarora221126.2K views
Java 103 intro to java data structures von agorolabs
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs3.3K views

Similar a Pi j3.4 data-structures

arrays-120712074248-phpapp01 von
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
147 views45 Folien
STRINGS IN JAVA von
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVALOVELY PROFESSIONAL UNIVERSITY
208 views56 Folien
Lecture 9 von
Lecture 9Lecture 9
Lecture 9talha ijaz
290 views18 Folien
Java 103 von
Java 103Java 103
Java 103Manuela Grindei
524 views53 Folien
ARRAYS.ppt von
ARRAYS.pptARRAYS.ppt
ARRAYS.pptsoniya555961
5 views11 Folien
Array von
ArrayArray
ArrayPRN USM
2.4K views61 Folien

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

arrays-120712074248-phpapp01 von Abdul Samee
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee147 views
Array von PRN USM
ArrayArray
Array
PRN USM2.4K views
Lecture_3.5-Array_Type Conversion_Math Class.pptx von ShahinAhmed49
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
ShahinAhmed494 views
4java Basic Syntax von Adil Jafri
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
Adil Jafri151 views
Multi dimensional arrays von Aseelhalees
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
Aseelhalees583 views
ARRAYS.ppt von coding9
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
coding92 views
Java OOP Programming language (Part 4) - Collection von OUM SAOKOSAL
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL297 views
Chapter 7.1 von sotlsoc
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc395 views

Más de mcollison

Pi j4.2 software-reliability von
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
106 views44 Folien
Pi j4.1 packages von
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packagesmcollison
92 views23 Folien
Pi j3.1 inheritance von
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
121 views24 Folien
Pi j3.2 polymorphism von
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
208 views22 Folien
Pi j2.3 objects von
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
122 views24 Folien
Pi j2.2 classes von
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classesmcollison
118 views15 Folien

Más de mcollison(11)

Pi j4.2 software-reliability von mcollison
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison106 views
Pi j4.1 packages von mcollison
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
mcollison92 views
Pi j3.1 inheritance von mcollison
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
mcollison121 views
Pi j3.2 polymorphism von mcollison
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison208 views
Pi j2.3 objects von mcollison
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
mcollison122 views
Pi j2.2 classes von mcollison
Pi j2.2 classesPi j2.2 classes
Pi j2.2 classes
mcollison118 views
Pi j1.0 workshop-introduction von mcollison
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
mcollison110 views
Pi j1.4 loops von mcollison
Pi j1.4 loopsPi j1.4 loops
Pi j1.4 loops
mcollison169 views
Pi j1.3 operators von mcollison
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
mcollison144 views
Pi j1.2 variable-assignment von mcollison
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
mcollison79 views
Pi j1.1 what-is-java von mcollison
Pi j1.1 what-is-javaPi j1.1 what-is-java
Pi j1.1 what-is-java
mcollison171 views

Último

Gross Anatomy of the Liver von
Gross Anatomy of the LiverGross Anatomy of the Liver
Gross Anatomy of the Liverobaje godwin sunday
89 views12 Folien
MIXING OF PHARMACEUTICALS.pptx von
MIXING OF PHARMACEUTICALS.pptxMIXING OF PHARMACEUTICALS.pptx
MIXING OF PHARMACEUTICALS.pptxAnupkumar Sharma
125 views35 Folien
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf von
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdfSTRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdfDr Vijay Vishwakarma
134 views68 Folien
Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf von
 Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf
Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdfTechSoup
62 views28 Folien
Retail Store Scavenger Hunt.pptx von
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptxjmurphy154
53 views10 Folien
JRN 362 - Lecture Twenty-Three (Epilogue) von
JRN 362 - Lecture Twenty-Three (Epilogue)JRN 362 - Lecture Twenty-Three (Epilogue)
JRN 362 - Lecture Twenty-Three (Epilogue)Rich Hanley
43 views57 Folien

Último(20)

Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf von TechSoup
 Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf
Ask The Expert! Nonprofit Website Tools, Tips, and Technology.pdf
TechSoup 62 views
Retail Store Scavenger Hunt.pptx von jmurphy154
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptx
jmurphy15453 views
JRN 362 - Lecture Twenty-Three (Epilogue) von Rich Hanley
JRN 362 - Lecture Twenty-Three (Epilogue)JRN 362 - Lecture Twenty-Three (Epilogue)
JRN 362 - Lecture Twenty-Three (Epilogue)
Rich Hanley43 views
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37 von MysoreMuleSoftMeetup
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
ANGULARJS.pdf von ArthyR3
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
ArthyR352 views
INT-244 Topic 6b Confucianism von S Meyer
INT-244 Topic 6b ConfucianismINT-244 Topic 6b Confucianism
INT-244 Topic 6b Confucianism
S Meyer49 views
Nelson_RecordStore.pdf von BrynNelson5
Nelson_RecordStore.pdfNelson_RecordStore.pdf
Nelson_RecordStore.pdf
BrynNelson550 views
EILO EXCURSION PROGRAMME 2023 von info33492
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023
info33492208 views
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice von Taste
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a ChoiceCreative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice
Taste52 views
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... von Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
11.30.23A Poverty and Inequality in America.pptx von mary850239
11.30.23A Poverty and Inequality in America.pptx11.30.23A Poverty and Inequality in America.pptx
11.30.23A Poverty and Inequality in America.pptx
mary850239181 views
Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv... von Taste
Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv...Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv...
Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv...
Taste62 views
Introduction to AERO Supply Chain - #BEAERO Trainning program von Guennoun Wajih
Introduction to AERO Supply Chain  - #BEAERO Trainning programIntroduction to AERO Supply Chain  - #BEAERO Trainning program
Introduction to AERO Supply Chain - #BEAERO Trainning program
Guennoun Wajih123 views

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