Java Syntax - Common Data Structures Flashcards
Array definition
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Initialize a one dimensional array that can hold 10 integers
int[] myArr = new int[10];
Initialize a two dimensional array of integers with 10 rows and 20 columns
int[][] myArr = new int[10][20];
Initialize an array containing the integers 1, 2, and 3
int[] myArr = new int[]{1, 2, 3};
or
int[] myArr = {1, 2, 3};
Initialize a two dimensional array with 3 rows and 3 columns:
1, 2, 3
4, 5, 6
7, 8, 9
int[][]myArr={{1,2,3},{4,5,6},{7,8,9}}
Iterate through an array
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
for (int i : array) {
System.out.print(array[i]);
}
String creation
String s = new String(“hello”);
String s = “hello”;
String size
s.length()
Accessing and iterating through characters in a String, s.
char[] charArray = s.toCharArray();
for (int i = 0; i < charArray.length; i++) {
System.out.print(charArray[i]);
}
for (int i = 0; i < s.length(); i++) {
System.out.print(s.charAt(i));
}
HashMap definition
A HashMap is a data structure that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value.
HashMap
- Create a new HashMap mapping String to String
- Add an element
- Update element
- Remove element
- Size
- Iterate through entry set
- Iterate through key set
- Iterate through values
- Create a new HashMap:
HashMap map = new HashMap<>();
- Add an element:
map. put(“key”, “value”); - Update element:
map. put(“key”, map.getOrDefault(“key”, “updatedValue”); - Remove element:
map. remove(“key”); - Size
map. size(); - Iterate through entry set
for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + “ “ +
entry.getValue());
}
- Iterate through key set
for (String key : map.keySet()) {
System.out.println(key);
}
- Iterate through values
for (String value : map.values()) {
System.out.println(value);
}
HashMap Time Complexity
- Access
- Search
- Insert
- Remove
- Access: O(1)
- Search: O(n)
- Insert: O(1)
- Remove: O(1)
HashSet definition
A HashSet is a collection that uses a Hash table for storage, only allowing unique elements to be added.
HashSet
- Create a new HashSet of String
- Add an element
- Remove element
- Search element
- Size
- Iterate through set
- Create a new HashSet of String:
HashSet set = new HashSet<>();
- Add an element:
set. add(“hello”); - Remove element:
set. remove(“hello”); - Search element:
set. contains(“hello”); - Size:
set. size(); - Iterate through set:
for(String s : set) {
System.out.println(s);
}
HashSet Time Complexity
- Access
- Search
- Insert
- Remove
- Access: O(1)
- Search: O(1)
- Insert: O(1)
- Remove: O(1)