COMP2511
25T1 Week 8
Thursday 9am-12pm (H09B)
Slides by Sam Zheng (z5418112)
Original slides by Alvin Cherk
This week
- Generic programming
- Singleton pattern
Admin
No lab marking in week 10.
Means that all labs must be marked in week 9.
This week's lab exercises are the final lab.
There will be a sample exam with the exam environment in week 10. I highly encourage you to attend if you want to be familiar with the exam layout and exam environment.
Admin - Assignments
- Assignment 2 - please make a start if you haven't already!
- Due Week 9 Friday, 3pm (18th April)
- No extensions (even for special cons/ELP). Mark leniency is applied instead.
- Any group work issues please let me know as soon as possible!
- Assignment 3
- Optional assignment - regain up to 8% of lost marks in A1/A2
- Can be completed in pairs or individually
- We assume your Assignment 2 groups by default, unless you have a group of 3
- If you wish to change groups/work individually let me know via Teams or email :)
Generic Programming
Generic Programming
What are generics?
Generics enable types to be passed when defining classes, interfaces or methods
- Remove casting and offer stronger type checks at compile time
- Allow implementations of generic algorithms, that work on a collection of different types
- Adds stability to code by making more of your bugs detectable at run-time
- You've already used them, likely without knowing!
List<String> list = new ArrayList<>();
list.add("Hello");
String str = list.get(0); // Type-safe, no casting requiredGeneric Programming
List<Type> name = new ArrayList<Type>();
- We can specify the type of elements, say in an ArrayList inside of the <> brackets.
- We say that the ArrayList class accepts a type parameter, or that it is a generic class.
- If we don't specify a type, we will get a warning from our compiler.
List<String> list = new ArrayList<>();
list.add("Hello");
String str = list.get(0); // Type-safe, no casting required
Dog woof = (Dog) list.get(1); // We can't do thisGeneric Programming
- We can make ourselves a generic class
- This means that whenever we construct this object, we must give a type parameter
- The rest of your class code can access that type by name
- Beware that you cannot create objects of a parameterised type!
- Convention:
- T for Type
- E for Element
- N for Number
- K for Key
- V for Value
- Convention:
public class Foo1<T> {
public void Bar(T val) {}
}
public class Foo2<K, V> {
public void Bar(K key, V val) {
// this is not valid
someVar = new K();
}
}Generic Programming
- If you don't want to scope a generic type to the entire class, you can do it for a single method.
public class Foo1<T> {
public static <S> void Bar(List<S> stuff) {
// do stuff
// S and T accessible
}
public static void Bar2() {
// only T accessible
}
}
Generic Programming
- We can also apply bounds to our type parameters
- Instead of just being any generic type, we can do for example:
- <T extends Number> - T can be Number or any subclass of Number, like Integer
- <? super Integer> - this means that we can hold Integer or any superclass of Integer, like Number or Object
public class Foo {
public static <T extends Number> void Bar(List<T> stuff) {
Number n = stuff.get(0); // this is fine
Integer n1 = stuff.get(1); // can't ascertain this is an integer
stuff.add("abc"); // can't do this
}
}
Generic Programming
- ? is a wild-card type parameter, one that can be of any type
- The difference between List<?> and List<Object> is that ? can become any type, while List<Object> for example wouldn't take List<String>
public class Foo {
public static void Bar(List<? extends Number> stuff) {
for (Number number : list) {
System.out.println(number); // Can print any subclass of Number
}
}
}
Generic Programming
/**
* How many different types of T here?
*
* It's all about the scope
*/
public class ConfusingClass<T> {
private T t1;
public <T> T t2(T t) {
return null;
}
public static <T> T t3(T t) {
return null;
}
public static void main(String[] args) {
ConfusingClass<String> cc = new ConfusingClass<String>();
cc.t2(3);
}
}Example from Webster
Generic Programming
class ConfusingClass<T1> {
private T1 t1;
// private T2 t2; // nope
// private T3 t3; // nope
public <T2> T2 t2(T2 t) {
T1 t1;
T2 t2;
// T3 t3; // nope
return null;
}
// ConfusingClass.t3(...)
public static <T3> T3 t3(T3 t) {
// T1 t1; // nope
// T2 t2; // nope
T3 t3;
return null;
}
}Example from Webster
Code Demo
Stack.java
Code Demo
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:
- What is
E?- A generic type
- What is the
Iterableinterface? Why does it have anEas well? What methods does it force us to implement?- Iterable: Something that can be iterated over
- Forces us to implement the
.iterator()method
Code Demo
-
When completing
toArrayList, why do we need to make a copy rather then just returning our internalArrayList?-
Don't want to break encapsulation
-
- What does the
.iterator()method allow us to do? Look atStackTest.java- Allows us to loop through it like a normal collection in a standardized way
Code Demo
public static Integer sumStack(Stack<? extends Integer> stack);- What does the
<? extends Type>and<? super Type>mean?-
extends: the parameterized type must be a class or subclass of the given type -
super: the parameterised type must be a class or super class of the given type
-
- What is the difference between
?andE?-
?can't be referred to as a type (Type erasure) -
Ecan
-
Singleton Pattern
Singleton Pattern
What type of pattern?
Creational pattern
The singleton pattern ensures that a class has only one instance. It provides a global access point to this instance.
It helps avoid initialisation overhead when only 1 copy of an instance is needed.

Code Demo
Heist.java

COMP2511 Week 8 25T1
By Sam Zheng
COMP2511 Week 8 25T1
- 127