This defines a class, so while enumerations can be simple like the following:
public enum Month{
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}
They can also have their own instance variables and methods.
public enum Month{
JANUARY (31),
FEBRUARY (27),
MARCH (31),
APRIL (30),
MAY (31),
JUNE(30),
JULY(31),
AUGUST(31),
SEPTEMBER(30),
OCTOBER(31),
NOVEMBER(30),
DECEMBER(31);
private final int numDays;
Month(int numDays){
this.numDays = numDays)
}
public int numberOfDays(){ return this.numDays;}
}
From the textbook:
ArrayList myArray = new ArrayList();
myArray.add(0 new Integer(47));
Integer myInt = (Integer)myArray.get(0);
ArrayList<String> names = new ArrayList<String>();
The type in the angle brackets becomes another parameter
Any name can be used, but T is traditional
public class MyClass<T> {
private T someVariable
public T getVariable()
{
return someVariable.clone();
}
}
public boolean allTheSame( ArrayList<?> list){
...
}
public boolean allTheSame2(ArrayList<? extends Number> list){
...
}
throw new Exception();
public void aMethod() throws Exception
{
...
//Something went wrong!
throw new Exception();
...
}
public static void main(String [] args){
...
try{
aMethod();
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
...
}
Class string = String.class
Method length = string.getMethod("length", null)
String s = "This is a string";
Object stringLength = length.invoke(s,null);
import java.util.function.Consumer;
public class LambdaScopeTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
// The following statement causes the compiler to generate
// the error "local variables referenced from a lambda expression
// must be final or effectively final" in statement A:
//
// x = 99;
Consumer<Integer> myConsumer = (y) ->
{
System.out.println("x = " + x); // Statement A
System.out.println("y = " + y);
System.out.println("this.x = " + this.x);
System.out.println("LambdaScopeTest.this.x = " +
LambdaScopeTest.this.x);
};
myConsumer.accept(x);
}
}
public static void main(String... args) {
LambdaScopeTest st = new LambdaScopeTest();
LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}