
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a diamond operator be used with an anonymous inner class in Java 9?
Yes, we can use the diamond operator with an anonymous inner class since Java 9.
The purpose of using a diamond operator is to avoid redundant code and make it more readable by no longer using a generic type on the right side of an expression. The diamond operator used only for normal classes but not for anonymous inner classes in Java 7. If we try to use it for anonymous inner classes, the compiler throws an error.
In the below example, we have used a diamond operator with an anonymous inner class.
Example
import java.util.*; public class DiamondOperatorTest { public static void main(String args[]) { String[] str = {"Raja", "Adithya", "Jai", "Chaitanya", "Vamsi"}; Iterator<String> itr = new Iterator<String>() { // Anonymous inner class int i = 0; public boolean hasNext() { return i < str.length; } public String next() { if(!hasNext()) { throw new NoSuchElementException(); } return str[i++]; } }; while(itr.hasNext()) { System.out.println(itr.next()); } } }
Output
Raja Adithya Jai Chaitanya Vamsi
- Related Questions & Answers
- How can we use a diamond operator with anonymous classes in Java 9?
- How are anonymous (inner) classes used in Java?
- How to implement an interface using an anonymous inner class in Java?
- Can an anonymous class have constructors in Java?
- What are anonymous inner classes in Java?
- Can you extend a static inner class in Java?
- What is an Inner class in Java?
- Inner class in Java
- Local inner class in Java
- Can a final class be subclassed in Java?
- How to instantiate a static inner class with reflection in Java?
- What are the different wildcard characters that can be used with MySQL LIKE operator?
- What are the different wildcard characters which can be used with NOT LIKE operator?
- What are the different wildcard characters that can be used with MySQL RLIKE operator?
- How many types of anonymous inner classes are defined in Java?
Advertisements