The most heavily used class from IJDK, possibly other than Str, is Array. This post compares the implementations of common idioms, using the JDK java.util.ArrayList and org.incava.ijdk.collect.Array classes.

Creating

Empty

    ArrayList<Integer> list = new ArrayList<>();

    // more explicit that the array is empty (but mutable);
    // no need to use <> or <Integer>:
    Array<Integer> ary = Array.empty();

With Elements

    // Arrays.asList returns an immutable array, so ArrayList has to wrap it:
    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3, 17, 212));

    // how concise
    Array<Integer> ary = Array.of(3, 17, 212);
    list        : [3, 17, 212]
    ary         : [3, 17, 212]

Accessing

Get

    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(60, 16, 252, 9, 3, 17));
    Array<Integer> ary = Array.of(60, 16, 252, 9, 3, 17);
    
    Integer n;

    n = list.size() > 0 ? list.get(list.size() - 1) : null;
    // n           : 17
    n = list.size() > 0 ? list.get(list.size() - 2) : null;
    // n           : 3
    n = list.size() >= 8 ? list.get(8) : null;
    // n           : null
    n = list.size() > 8 ? list.get(list.size() - 8) : null;
    // n           : null
    
    n = ary.get(-1);
    // n           : 17
    n = ary.get(-2);
    // n           : 3
    n = ary.get(8);
    // n           : null    
    n = ary.get(-8);
    // n           : null    

Append (Add)

    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3, 7, 23, 50));

    Array<Integer> ary = Array.of(3, 7, 23, 50);

    list.add(2);
    list.add(8);
    list.add(6);
    // list        : [3, 7, 23, 50, 2, 8, 6]

    // chaining appends:
    ary.append(2).append(8).append(6);
    // ary         : [3, 7, 23, 50, 2, 8, 6]

First, Last

    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(60, 16, 252, 9, 3, 17));
    Array<Integer> ary = Array.of(60, 16, 252, 9, 3, 17);        

    Integer n;
    
    n = list.size() > 0 ? list.get(0) : null;
    // n           : 60
    n = ary.first();
    // n           : 60

    n = list.size() > 0 ? list.get(list.size() - 1) : null;
    // n           : 17
    n = ary.last();
    println("n", n);

    n = list.size() > 0 ? list.remove(0) : null;
    println("n", n);
    println("list", list);

    n = ary.takeFirst();
    println("n", n);
    println("ary", ary);

    n = list.size() > 0 ? list.remove(list.size() - 1) : null;
    println("n", n);
    println("list", list);

    n = ary.takeLast();
    println("n", n);
    println("ary", ary);

We think in generalities, but we live in detail. – Alfred North Whitehead

Related