Skip to lesson

Constructor references

A constructor reference such as ArrayList::new or Student::new is a short form of a lambda that only calls a constructor. The target interface decides which constructor runs, and every call creates a new object.

ClassName::new as a Supplier

Constructor reference is a method reference written ClassName::new. It calls a constructor each time the interface method runs, and the inputs of the interface are passed to that constructor.

A constructor reference is ClassName::new. It is the short form of a lambda that only calls a constructor: ArrayList::new is () -> new ArrayList<>(), and HashMap::new is () -> new HashMap<>().

Example 1 · Supplier: every get() builds a new object

SupplierCtorDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.function.Supplier;
public class SupplierCtorDemo {    public static void main(String[] args) {        Supplier<List<String>> newList = ArrayList::new;          // () -> new ArrayList<>()        Supplier<Map<String, Integer>> newMap = HashMap::new;      // () -> new HashMap<>()        Supplier<StringBuilder> newBuilder = StringBuilder::new;   // () -> new StringBuilder()
        List<String> sectionA = newList.get();        List<String> sectionB = newList.get();        sectionA.add("Asha");        System.out.println("A: " + sectionA + ", B: " + sectionB);        System.out.println("Same object? " + (sectionA == sectionB));
        Map<String, Integer> fees = newMap.get();        fees.put("Asha", 25000);        System.out.println(fees);
        StringBuilder receipt = newBuilder.get().append("Paid Rs ").append(25000);        System.out.println(receipt);    }}
Output
A: [Asha], B: []
Same object? false
{Asha=25000}
Paid Rs 25000

What this code does

  • Each get() runs the constructor again, so sectionA and sectionB are two separate lists. Adding to one does not touch the other.
  • The type arguments come from the target: Supplier<Map<String, Integer>> makes HashMap::new build a HashMap<String, Integer>.

Why pass a constructor around at all? Sometimes a method must create objects but should not decide their class. A method that collects results can accept a Supplier<List<String>> and call get() whenever it needs a fresh list. The caller chooses ArrayList::new or LinkedList::new. A factory is any code whose job is to create objects, and a constructor reference is the smallest possible factory. Unlike a bound reference, nothing is created when the reference is written. Every get() runs the constructor again and returns a new object.

Generic types are inferred from the target: Supplier<List<String>> s = ArrayList::new; creates an ArrayList<String>, with no <> needed after the class name.

Which constructor is chosen

A class can have several constructors. The reference Student::new does not say which one, so Java picks the constructor whose parameters match the inputs of the interface, in order.

The same Student::new picks a different constructor for each interface. Supplier<Student> needs Student(). Function<String, Student> needs Student(String). BiFunction<String, Integer, Student> needs Student(String, int).

Example 2 · The interface picks the constructor

WhichCtorDemo.javaJava
import java.util.function.BiFunction;import java.util.function.Function;import java.util.function.Supplier;
class Student {    private final String name;    private final int marks;
    Student() {        this("Unknown", 0);    }
    Student(String name) {        this(name, 0);    }
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class WhichCtorDemo {    public static void main(String[] args) {        Supplier<Student> blank = Student::new;                        // Student()        Function<String, Student> named = Student::new;                // Student(String)        BiFunction<String, Integer, Student> full = Student::new;      // Student(String, int)
        System.out.println(blank.get());        System.out.println(named.apply("Ravi"));        System.out.println(full.apply("Meera", 91));    }}
Output
Unknown(0)
Ravi(0)
Meera(91)

What this code does

  • The text Student::new is the same on all three lines. The interface decides: no input picks Student(), one String picks Student(String), a String and an Integer pick Student(String, int).
  • In the BiFunction, the Integer input is unboxed to the int the constructor wants, just as in a normal call.

Example 3 · Real use: build objects from text input

FromTextDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.BiFunction;import java.util.function.Function;
record Applicant(String name, int marks) {}
class Ticket {    private final String id;
    Ticket(String id) {        this.id = id.trim().toUpperCase();    }
    @Override    public String toString() {        return "Ticket " + id;    }}
public class FromTextDemo {    static <T> List<T> buildAll(List<String> lines, Function<String, T> maker) {        List<T> out = new ArrayList<>();        for (String line : lines) {            out.add(maker.apply(line));        }        return out;    }
    public static void main(String[] args) {        // simple one-field objects: the constructor itself is the maker        System.out.println(buildAll(List.of(" pnr881 ", "pnr902"), Ticket::new));
        // two fields: split each line, then call the canonical constructor        BiFunction<String, Integer, Applicant> make = Applicant::new;        List<Applicant> list = new ArrayList<>();        for (String line : List.of("Asha,91", "Ravi,78", "Meera,85")) {            String[] parts = line.split(",");            list.add(make.apply(parts[0], Integer.parseInt(parts[1])));        }        list.forEach(System.out::println);    }}
Output
[Ticket PNR881, Ticket PNR902]
Applicant[name=Asha, marks=91]
Applicant[name=Ravi, marks=78]
Applicant[name=Meera, marks=85]

What this code does

  • buildAll turns text into objects of any type. Passing Ticket::new makes it call new Ticket(line) for every line, and T becomes Ticket.
  • A record's canonical constructor takes all its components, so Applicant::new fits BiFunction<String, Integer, Applicant>. Parsing stays in the loop; the reference only builds.
  • Supplier<T> → the no-argument constructor T().
  • Function<A, T> → a constructor T(A).
  • BiFunction<A, B, T> → a constructor T(A, B).
  • More than two values → write your own functional interface, or a lambda.

With Supplier<Student> (no inputs), Java needs Student(). With Function<String, Student> (one String), it needs Student(String). With BiFunction<String, Integer, Student>, it needs Student(String, int), unboxing the Integer. The interface's result type must accept the new object. If no constructor fits, the code does not compile. A record has only its canonical constructor, the one with all components, unless you add more. So Supplier<Student> fails for record Student(String name, int marks).

Fix the error

Fix the constructor reference

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

A record has only the constructor with all its parts.

import java.util.function.*;
public class CtorFix {
record Student(String name, int marks) { }
public static void main(String[] args) {
Supplier<Student> maker = Student::new;
System.out.println(maker.get());
}
}

Error

CtorFix.java:7: error: incompatible types: invalid constructor reference
        Supplier<Student> maker = Student::new;
    constructor Student in record Student cannot be applied to given types
      required: String,int

Array constructor references

Arrays have constructor references too: String[]::new is size -> new String[size], and int[]::new is size -> new int[size]. Their target is an IntFunction, because the only input is the length.

Example 4 · Array constructor references: String[]::new and int[]::new

ArrayCtorDemo.javaJava
import java.util.Arrays;import java.util.List;import java.util.function.IntFunction;
public class ArrayCtorDemo {    public static void main(String[] args) {        List<String> toppers = List.of("Asha", "Divya", "Ravi");
        String[] asArray = toppers.toArray(String[]::new);   // size -> new String[size]        System.out.println(asArray.length + " " + Arrays.toString(asArray));
        IntFunction<int[]> marksSheet = int[]::new;            // size -> new int[size]        int[] marks = marksSheet.apply(4);        marks[0] = 88;        System.out.println(Arrays.toString(marks));
        IntFunction<String[]> seats = String[]::new;        String[] row = seats.apply(3);        Arrays.fill(row, "free");        row[1] = "booked";        System.out.println(Arrays.toString(row));    }}
Output
3 [Asha, Divya, Ravi]
[88, 0, 0, 0]
[free, booked, free]

What this code does

  • String[]::new takes one int, the length, and returns a new String[]. That is the shape of IntFunction<String[]>, which toArray accepts, so the result is a real String[].
  • int[]::new works the same for primitive arrays. A new int[] starts with zeros and a new String[] with null, exactly like new int[4].

The most common use is list.toArray(String[]::new). Since Java 11, a collection can take an IntFunction that creates an array of the right type and size. The result is a real String[], not an Object[], so no cast is needed. The Streams sections use the same reference with stream.toArray(String[]::new).

Map factories and a hidden constructor trap

Map constructors make good factories: TreeMap::new keeps keys sorted, LinkedHashMap::new keeps insertion order, HashMap::new keeps no order. A method that builds a map can take a Supplier<Map<String, Integer>> and let the caller choose. The stream collectors module passes these same references to groupingBy and toMap.

Example 5 · Map factories: let the caller choose the order

MapFactoryDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.function.Supplier;
public class MapFactoryDemo {    static Map<String, Integer> countVotes(List<String> votes, Supplier<Map<String, Integer>> mapMaker) {        Map<String, Integer> result = mapMaker.get();        for (String v : votes) {            result.merge(v, 1, Integer::sum);        }        return result;    }
    public static void main(String[] args) {        List<String> votes = List.of("Ravi", "Asha", "Zoya", "Asha", "Ravi", "Asha");        System.out.println("First vote order: " + countVotes(votes, LinkedHashMap::new));        System.out.println("Name order:       " + countVotes(votes, TreeMap::new));    }}
Output
First vote order: {Ravi=2, Asha=3, Zoya=1}
Name order:       {Asha=3, Ravi=2, Zoya=1}

What this code does

  • countVotes creates its map through the Supplier, so it never names a map class. LinkedHashMap::new keeps the order in which names first appeared; TreeMap::new sorts by name.
  • This "pass the factory" style returns in the Collectors module, where groupingBy and toMap accept TreeMap::new to pick the result map.

Example 6 · Trap: computeIfAbsent with ArrayList::new

ComputeTrapDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;
public class ComputeTrapDemo {    public static void main(String[] args) {        // Integer keys: compiles, but calls new ArrayList<>(2024): 2024 is used as a capacity        Map<Integer, List<String>> byYear = new TreeMap<>();        byYear.computeIfAbsent(2024, ArrayList::new).add("Asha");        byYear.computeIfAbsent(2025, ArrayList::new).add("Ravi");        System.out.println(byYear);
        // String keys: byBranch.computeIfAbsent("CSE", ArrayList::new) would not compile        // (no ArrayList(String) constructor). Say what you mean with a lambda:        Map<String, List<String>> byBranch = new TreeMap<>();        byBranch.computeIfAbsent("CSE", k -> new ArrayList<>()).add("Meera");        byBranch.computeIfAbsent("ECE", k -> new ArrayList<>()).add("John");        byBranch.computeIfAbsent("CSE", k -> new ArrayList<>()).add("Divya");        System.out.println(byBranch);    }}
Output
{2024=[Asha], 2025=[Ravi]}
{CSE=[Meera, Divya], ECE=[John]}

What this code does

  • computeIfAbsent passes the key to its function. With Integer keys, ArrayList::new matches ArrayList(int initialCapacity), so each year silently builds a list with room for 2024 items. The output looks right, which hides the waste.
  • With String keys there is no ArrayList(String) constructor, so the reference does not compile. k -> new ArrayList<>() ignores the key on purpose and works for every key type.

One trap: map.computeIfAbsent(key, ArrayList::new). computeIfAbsent wants a Function that receives the key. With a String key, Java looks for ArrayList(String), finds none, and the code does not compile. With an Integer key, or a Character key that widens to int, it compiles, but it calls ArrayList(int initialCapacity), which uses the key as the starting size. A key of one million builds a large empty array for nothing. Write k -> new ArrayList<>() there. The lambda ignores the key and says exactly what you mean.

Next step

Check your understanding

11 quick questions