What is this?
Benefits
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.
Answer the following questions:
E
?
E
as well? What methods does it force us to implement?
toArrayList
, why do we need to make a copy rather than just returning our internal ArrayList
?
.iterator()
method allow us to do? Discuss the test inside StackTest.java
.
public static Integer sumStack(Stack<? extends Integer> stack);
<? extends Type>
and <? super Type>
mean?
?
and E
?
What is this?
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
Benefits
It helps avoid initialisation overhead when only 1 copy of an instance is needed.
Consider the Bank Account class from Lab 04. What if multiple people try to access the bank account at the same time? Inside src/unsw/heist
are three classes:
BankAccount
, from Lab 04.BankAccountAccessor
. Objects of this type are an instance of an access to a bank account to withdraw money a given number of times by given amounts.BankAccountThreadedAccessor
, which extends Thread
, and overrides the method run to create a new instance of BankAccountAccessor
and access the bank.
Currently, when you run the code, you will find that each thread accesses the bank at the same time (which doesn't make sense). In some cases some strange behaviour is produced by this race condition:
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
Use the Singleton Pattern to ensure that only one person can access the bank at a time. You can assume for simplicity's sake that only one access to any bank account can ever be made at a given time.