- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a constructor reference for an array in Java?
A constructor reference is similar to method reference except that the name of a method is new. We can also create a constructor reference with an array type. For instance, if we need to create an integer array by using the constructor reference: int[]:: new, where the parameter is a length of an array.
Syntax
ArrayTypeName[]::new
Example
@FunctionalInterface interface ArrayCreator { int[] makeArray(int number); } public class ArrayConstructorRefTest { public static void main(String[] args) { ArrayCreator arrayCreator = int[]::new; // Constructor Reference for an Array int[] intArray = arrayCreator.makeArray(10); for(int i = 0; i < intArray.length; i++) { intArray[i] = i * i - i / 2; System.out.println("[" + i + "] = " + intArray[i]); } } }
Output
[0] = 0 [1] = 1 [2] = 3 [3] = 8 [4] = 14 [5] = 23 [6] = 33 [7] = 46 [8] = 60 [9] = 77
Advertisements