What is it?
Style of programming that allow types to be used as a parameter to methods, classes and interfaces.
What is it?
Style of programming that allow types to be used as a parameter to methods, classes and interfaces.
Why would you use it?
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
public class Box<T, S> {
private T value1;
private S value2;
public Box(T value1, S value2) {
this.value1 = value1;
this.value2 = value2;
}
public void setValue(T value1, S value2) {
this.value1 = value1;
this.value2 = value2;
}
public T getValue1() {
return value1;
}
public S getValue2() {
return value2;
}
}
Inside src/stack
, there are a series of stubs for a Stack class which takes in a generic type. There are a series of tests inside StackTest.java
which currently fail.
Implement the methods so that the tests pass, using an ArrayList
to store the internal data structure.
What methods does it force us to implement?
.iterator()
methodWhy does the Iterable
interfacehas an E
as well?
.next()
returns elements of type E
What is the Iterable
interface
public static Integer sumStack(Stack<? extends Integer> stack);
<? extends Type>
and<? super Type>
mean??
and E
?What is this?
Creational design pattern that specifies that a class can only have one instance. Accessing the instance must be via a global access point.
Why use it?
The instance is only created when the getInstance
method is first called.
Currently, the threads can all access the bank account at the same time. This can lead to undesirable behaviour like
Denver is accessing the bank.
Tokyo is accessing the bank.
The final balance is: $100
Rio is accessing the bank.
Rio successfully withdrew $20
Tokyo successfully withdrew $6
Denver successfully withdrew $49
Tokyo successfully withdrew $6
Denver failed to withdraw $49.
Rio successfully withdrew $20
Rio failed to withdraw $20.
Denver is leaving the bank, the balance is -1
Tokyo failed to withdraw $6.
Rio failed to withdraw $20.
Tokyo failed to withdraw $6.
Rio failed to withdraw $20.
Tokyo failed to withdraw $6.
Tokyo failed to withdraw $6.
Rio is leaving the bank, the balance is -1
Tokyo is leaving the bank, the balance is -1
Bank account only had $100 but $101 was taken out!
The undesired behaviour is caused race conditions
Refactor using the Singleton Pattern to ensure only one person can access the bank account at a time!