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