Java) generics/ enum/ annotation
This post was migrated from Tistory. You can find the original here.
Generics
Wildcards
1
2
ArrayList<? extends Product> list = new ArrayList<Tv>();
ArrayList<? extends Product> list = new ArrayList<Audio>();
This applies polymorphism to generics.
There are cases where you don’t need to specify a generic type explicitly, but when you do need to, it seems useful for narrowing the generic scope down to two or more related types. The example shows this being used for a parameter. page 470
Generic methods
1
2
3
4
5
static <T extends Fruit> Juice makeJuice(FruitBox<T> box){
String tmp = "";
for(Fruit f : box.getList()) tmp += f+" ";
return new Juice(tmp);
}
You can declare a generic type on a method itself.
A method-level generic type is scoped locally, separate from any T defined on the enclosing generic class.
Using a method generic lets you declare and use a type parameter even on a static method.
enum
Adding members
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
enum Direction2 {
EAST(1, ">"), SOUTH(2,"V"), WEST(3, "<"), NORTH(4,"^");
private final int value;
private final String symbol;
Direction2(int value, String symbol) { // the private access modifier is omitted
this.value = value;
this.symbol = symbol;
System.out.printf("initial : %d=%s\n", value, symbol);
}
public int getValue() { return value; }
public String getSymbol() { return symbol; }
}
class Main {
public static void main(String[] args) {
for(Direction2 d : Direction2.values())
System.out.printf("%s=%d%n", d.name(), d.getValue());
}
}
result
initial : 1=>
initial : 2=V
initial : 3=<
initial : 4=^
EAST=1
SOUTH=2
WEST=3
NORTH=4
The fact that the constructor is private makes sense — it looks like enum constants are automatically created the moment the enum is first used.
If Main never references the enum, it never gets initialized.
annotation
Standard annotations provided by Java
@Override, @Deprecated, @SuppressWarnings, @FunctionalInterface.....
Standard annotations give the compiler useful information — catching a misspelled @Override, suppressing warnings, checking whether an interface is a valid functional interface, and so on.