Final Review of Lessons 7-10
Me attempting to do the work and be responsible
7.1 Intro to ArrayLists
- Arrays: Static, Static (fixed size), Fundamental java feature, An object with no methods, Not as flexible, Can store more primitive data, Slightly slower than Arrays
- ArrayLists: Dynamic (can change size) Part of a framework, A class with many methods, Designed to be more flexible, Store object references, Can only be used with an import statement
Primitive Data Types:
- boolean
- char
- double
- int
Wrapper Class Data Types (Store the primitive values as objects)
- Boolean
- Character
- Double
- Integer
7.2 ArrayList Methods
size(); --> Returns the number of elements in the list add(obj); --> Adds element at the end add(index, object); --> Adds element at specific index remove(index); --> Removes element from specific index set(index, object); --> Replaces element at index with new object get(index); --> Returns element at index
7.6 Sorting
- Selection sort identifies either the maximum or minimum of the compared values and iterates over the structure checking if the item stored at the index matches the condition, if so, it will swap the value stored at the index and continue.
- The insertion sort is characterized by building a sorted structure as it proceeds. It inserts each value it finds at the appropriate location in the data structure. This is often accomplished by using a while loop as the inner loop.
2D Array Vocab
Array = a data structure used to implement a collection (list) of primitive or object reference data Element = a single value in the array Index = the position of the element in the array (starts from 0) Array Length = the number of elements in the array
- Is public, so can be accessed in any class
- Is also final, so can’t change it after array has been created
The Basics
A 2D array is an array of arrays and can be a better way to store data Declaring a 2D array:
- ``DataType[][] nameOf2DArray``
Initializing a 2D array
- ``DataType[][] nameOf2DArray = new DataType[r][c];``
- r = # of rows
- The # of arrays in the array
- r = list.length
- c = # of columns
- The # of elements in the inner arrays
- ``c = list[0].length``
public class Test {
public static void main(String[] args) {
int[][] arr = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
System.out.println("arr[0][0] = " + arr[0][0]);
System.out.println("arr[1][2] = " + arr[1][2]);
System.out.println("arr[2][1] = " + arr[2][1]);
}
}
Test.main(null);
list[list.length - 1][list[0].length - 1]
- Updating an element:
list[r][c] = value;
public class Test {
public static void main(String[] args) {
String[][] arr = {
{ "a", "f", "g", "l" },
{ "b", "e", "h", "k" },
{ "c", "d", "i", "j" }
};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
System.out.print(arr[row][col] + " ");
}
System.out.println(" ");
}
}
}
Test.main(null);
public class Test {
public static void main(String[] args) {
String[][] arr = {
{ "Atlanta", "Baltimore", "Chicago" },
{ "Australia", "Boston", "Cincinnati" },
{ "Austin", "Beaumont", "Columbus" }
};
String match = "";
String name = "Boston";
for (String[] row : arr) {
for (String item : row) {
if (item.equals(name)) {
match = name;
}
}
}
if (match.length() == 0) {
System.out.println("No Match!");
} else {
System.out.println(name);
}
}
}
Test.main(null);
public class Car {
protected String brandName;
protected double range;
protected double doorNumber;
protected double maxSpeed;
// Constructor for the attributes present in the superclass
public Car(String brandName, double range, double doorNumber, double maxSpeed) {
this.brandName = brandName;
this.range = range;
this.doorNumber = doorNumber;
this.maxSpeed = maxSpeed;
}
public void gas () {
System.out.println("Go!");
}
public void brake () {
System.out.println("Stop!");
}
public void gearShift () {
System.out.println("Use the stick");
}
public void steer () {
System.out.println("turning left...");
}
public void horn () {
System.out.print("honking... ");
}
}
public class TeslaModelS extends Car {
// Additional attribute not present in the superclass
protected String hornSound;
// Constructor for Subclass
public TeslaModelS(String brandName, double range, double doorNumber, double maxSpeed, String hornSound) {
// We use the Superclass constructor for the shared attributes through the keyword "super"
super(brandName, range, doorNumber, maxSpeed);
// hornSound is not in the Superclass, so we add it separately in the constructor
this.hornSound = hornSound;
}
// We use override to change the functionality in the subclass of an existing method in the superclass
@Override
public void gearShift () {
System.out.println("Use the gear selector next to the wheel");
}
public void steer () {
System.out.println("turning right...");
}
// Here, we don't fully change the functionality of the existing horn method in the superclass
// Instead, we take all of the functionality of the superclass method, and then add on to it
public void horn () {
super.horn();
System.out.println(hornSound);
}
public static void main(String[] args) {
// 5 argument constructor
TeslaModelS modelS = new TeslaModelS("Tesla", 396, 4, 200, "eugh");
// Example of late binding
Car car = new TeslaModelS("Tesla", 396, 4, 200, "brrr");
// We can still use the methods from the child class, even though we didn't mention them in the subclass!
modelS.gas();
// Using the overridden method
modelS.gearShift();
modelS.steer();
// Using the method we added on to
modelS.horn();
car.horn();
}
}
TeslaModelS.main(null);
Super Keyword
- super keyword --> use constructors in the superclass and methods in the superclass in a child class
- TeslaModelS --> super keyword can be found in constructor and the method horn
- When it says super(brandName, range, doorNumber, maxSpeed) in the constructor, super keyword is used to utilize super class constructor inside child class
- super.horn() calling horn() from parent class Car
Creating References Using Inheritance Hierarchies
- Type diagram: similar appearance to a family tree. A is superclass/head of the family. Descendants are subclasses
- public class A public class B extends A public class C extends B
- A reference refers to an object of the class or object of an inherited class
Polymorphism
- means "many forms" --> one thing in many ways through inheritance
- can have two different implementations through overriding methods
- This is known as Runtime Polymorphism
- Method overloading: two methods with same name but different arguments and functionalities
- Compile Time Polymorphism or Static Polymorphism
- Early binding: when compiler decides which method should be called
- Late binding: when method is decided at runtime
Object Superclass
- Important things to know
- Object class is superclass of all other classes in java
- Object is part of the java.lang package --> known for imports
- Important Object class methods include: boolean equals(Object x) & String toString()
- Object class' subclass override the equals and toStrong methods
- toString Method
- Prints out the attributes of an object
- Converts string object into a string
- equals Method
- Compares two strings
- Returns a boolean value of true if equal...otherwise returns false
10.1 Recursion
- Recursive method is a method that calls itself
- Two parts to the method:
- base case
- recursive case
- Base case reached where recursion stops and value is returned
- write first to avoid infinite recursion
- Recursive calls == part of a method
- Recursive methods have a call stack that keeps track of all times recursive function is called
- Recursions similar to loops --> recursion can be written as loops
- Iteration vs Recursion
- Iteration used when a set of instructions are executed repeatedly until the condition becomes false
- Recursion used when solution to a bigger problem can be expressed in terms of smaller problems
- Main difference: recursion uses funtion calls...iteration uses for and while loops
10.2 Binary Search, Linear Recursion, Selection Sort, and Merge Sort
-
Binary search algorithm:
- Data must be sorted
- Keep halving array until you find value
- more efficient than linear search
-
Linear Recursion:
- Function that only makes a single call to istelf each time it's run
-
Selection Sort:
- Repeatedly find the minimum element from the unsorted part and putting it at the end of the sorted
-
Merge Sort:
- Can be used to sort ArrayList structures
- Use divide and conquer algorithm
- divides input array into two halves, call itself for two halves, and then merges the two sorted halves
- merge() function is used for merging two halves