16 February 2021

Type Inference in Java

The Diamond Operator This is a type inference mechanism we have seen already. It can be applied when instantiating a generic clas. Here an example


ArrayList<String> al = new ArrayList<>();

From the left-hand side, Java infers that you are making an array list of strings in the call to new on the right.

Lambdas This is a an anonymous function.

Simplest:  arg(s) → expression;

x -> x*x    squaring function
() -> System.out.println("Cows")
(x,y) -> x + y

lambda x: x*x
lambda : print("Cows")
lambda x,y : x + y

You can have several lines here and you can create local variables.
In this case YOU MUST have an explicit return
x ->
{
    return x*x;
}
(String x, int y)
{
    //stuff
    return expr(x,y);
}
class Foo implements RealFunction
{
    public double call(double x)
    {
        return x*x;
    }
}

forEach Takes a consumer as an argument and applies it to each element of the iterable.

Comparator<T> Specifies this.

public int compare(T x, T y)
compare(x,y) = - compare(y,x)  
if x.equals(y), compare(x,y) → 0
Compaisons should be
transitive 
defined for all values (linear order)

Idiom:

compare(x,y) < 0 means "x < y"
compare(x,y) > 0 means "x > y"
etc for the relational inequality operators

a = 1, 2, 3, 4, 5, 6, 7, 8 ...... b = 1, 4, 9, 16, 25...... (a*b)_0 = a_0*b_0 = 1 (a*b)_1 = a_0*b_1 + a_1*b_0 = 6 (a*b)_2 = a_2*b_0 + a_1*b_1 + a_0*b_2 = 3 + 8 + 9 = 20

Type Inference and Functional Interfaces

What is an Iterator<T>?

What is Iterable<T>??

The forEach method for Iterables

Warning! Things that are NOT True

Generics and Inheritance