Constructor references
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}A: [Asha], B: []
Same object? false
{Asha=25000}
Paid Rs 25000What this code does
- Each
get()runs the constructor again, sosectionAandsectionBare two separate lists. Adding to one does not touch the other. - The type arguments come from the target:
Supplier<Map<String, Integer>>makesHashMap::newbuild aHashMap<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.
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.
Example 2 · The interface picks the constructor
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)); }}Unknown(0) Ravi(0) Meera(91)
What this code does
- The text
Student::newis the same on all three lines. The interface decides: no input picksStudent(), oneStringpicksStudent(String), aStringand anIntegerpickStudent(String, int). - In the
BiFunction, theIntegerinput is unboxed to theintthe constructor wants, just as in a normal call.
Example 3 · Real use: build objects from text input
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); }}[Ticket PNR881, Ticket PNR902] Applicant[name=Asha, marks=91] Applicant[name=Ravi, marks=78] Applicant[name=Meera, marks=85]
What this code does
buildAllturns text into objects of any type. PassingTicket::newmakes it callnew Ticket(line)for every line, andTbecomesTicket.- A record's canonical constructor takes all its components, so
Applicant::newfitsBiFunction<String, Integer, Applicant>. Parsing stays in the loop; the reference only builds.
Supplier<T>→ the no-argument constructorT().Function<A, T>→ a constructorT(A).BiFunction<A, B, T>→ a constructorT(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.
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,intArray 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
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)); }}3 [Asha, Divya, Ravi] [88, 0, 0, 0] [free, booked, free]
What this code does
String[]::newtakes oneint, the length, and returns a newString[]. That is the shape ofIntFunction<String[]>, whichtoArrayaccepts, so the result is a realString[].int[]::newworks the same for primitive arrays. A newint[]starts with zeros and a newString[]withnull, exactly likenew 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
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)); }}First vote order: {Ravi=2, Asha=3, Zoya=1}
Name order: {Asha=3, Ravi=2, Zoya=1}What this code does
countVotescreates its map through theSupplier, so it never names a map class.LinkedHashMap::newkeeps the order in which names first appeared;TreeMap::newsorts by name.- This "pass the factory" style returns in the Collectors module, where
groupingByandtoMapacceptTreeMap::newto pick the result map.
Example 6 · Trap: computeIfAbsent with ArrayList::new
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); }}{2024=[Asha], 2025=[Ravi]}
{CSE=[Meera, Divya], ECE=[John]}What this code does
computeIfAbsentpasses the key to its function. WithIntegerkeys,ArrayList::newmatchesArrayList(int initialCapacity), so each year silently builds a list with room for 2024 items. The output looks right, which hides the waste.- With
Stringkeys there is noArrayList(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