Diamond Operator in Java
![]()
Diamond operator aka diamond syntax was introduced in Java 7 as a new feature. Purpose of the diamond operator is to simplify the use of generics when creating an object.
It avoids unchecked warnings in a program as well as reducing generic verbosity by not requiring explicit duplicate specification of parameter types.
Raw Types prior to Java 5
Before Java 5, the collections API supports only raw types. There was no way for type arguments be parameterized when constructing a collection.
The above code runs just fine, but suppose you also have the following:
Now we run into trouble at run-time, because the list contains something that isn’t an instanceof String.
Presumably, if you want names to contain only String, you could perhaps still use a raw type and manually check every add yourself, and then manually cast to String every item from names.
Generics from Java 5
Generics were introduced — which allowed us to parameterize the type arguments for classes,
Raw types refer to using a generic type without specifying a type parameter. For example, List is a raw type, while List<String> is a parameterized type.
When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java.
At this point, we have to specify the parameterized type in the constructor, which can be somewhat unreadable:
Even though the compiler still allows us to use raw types in the constructor,
it will prompt us with a warning message:
ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
Diamond Operator from Java 7
With Java 7, the diamond operator makes this shorter and simpler. It also adds type inference and reduces the verbosity in the assignments — when using generics:
It becomes even more useful with more complex data types, such as a List of Map objects as follows:
Simply put, the diamond operator adds the type inference feature to the compiler and reduces the verbosity in the assignments introduced with generics.
Generics allow us to keep the safety of generics with almost the same effort as using the raw type.
Java Diamond Operator
Before Java 7, while using generics we had to supply type parameters to variable types and to their actual types. Now, it has been relieved a bit. And a blank Java diamond operator on the right side of the declaration will work fine.
The diamond operator is denoted with two angles ‘< >’ .
1. Raw Type Declarations (Prior to Java 1.5)
If you have worked on early versions of Java (before 1.5), when generics were not a Java feature, developers have to use raw types declarations and initializations. For example, given below is a HashMap declarations.
The problem with this approach is that you can put any object type in key and value, and only in runtime, we will get the error if the object is not of the desired type. There is no compile-time safety that can warn developers, which types are allowed and which are not.
2. Parameterized Types in Java 1.5
JDK 1.5 brought generics. It was a much-needed feature and completely changed the way developers write code. It enabled compile time safety. It helped in reducing runtime errors by a great number.
This syntax solves the problem of compile-time type safety. In fact, the above syntax is good for almost all use cases. In the above example, if you try to add any key or value of a different type, the compiler will give you an error.
You need to fix your code to get through the compiler.
3. Diamond Operator since Java 1.7
Parameterized types solved a few issues but seem heavy due to the same repeated type of information on both sides. We can reduce the syntax if we can provide type information on one side, and another side can detect and apply the type information.
The diamond operator in Java does exactly the same thing. It is also called Elvis operator. Look below at the diamond operator syntax.
In the above code, the compiler is smart enough to identify that the diamond operator infers to type defined on the left-hand side of the declaration. It applies the type information to the right side object as well. It helps in adding type inference features to Java.
4. Backward Compatibility
Raw types and parameterized types still exist for the sake of backward compatibility. But new compilers will warn if they see raw types. If you compile raw types with Java 5 onward, you will get a warning like this:
ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized.
Руководство по Алмазному оператору на Java
Краткое и практическое руководство по алмазному оператору, которое было введено в Java 7.
- Автор записи
1. Обзор
В этой статье мы рассмотрим оператор diamond в Java и то, как generics и API коллекций повлияли на его эволюцию .
2. Необработанные Типы
До Java 1.5 API коллекций поддерживал только необработанные типы – при построении коллекции не было возможности параметризовать аргументы типа:
Это позволило добавить любой тип и привело к потенциальным исключениям приведения во время выполнения .
3. Дженерики
В Java 1.5 были введены дженерики– , которые позволили нам параметризовать аргументы типа для классов , в том числе в API коллекций – при объявлении и построении объектов:
На этом этапе мы должны указать параметризованный тип в конструкторе , который может быть несколько нечитаемым:
Причина такого подхода заключается в том , что необработанные типы все еще существуют для обеспечения обратной совместимости , поэтому компилятору необходимо различать эти необработанные типы и универсальные типы:
Несмотря на то, что компилятор по-прежнему позволяет нам использовать необработанные типы в конструкторе, он выдаст нам предупреждающее сообщение:
4. Алмазный оператор
Оператор diamond – введенный в Java 1.7 – добавляет вывод типов и уменьшает многословие в назначениях – при использовании дженериков :
Функция вывода типов компилятора Java 1.7 определяет наиболее подходящее объявление конструктора, соответствующее вызову .
Рассмотрим следующий интерфейс и иерархию классов для работы с транспортными средствами и двигателями:
Давайте создадим новый экземпляр Car с помощью оператора diamond:
Внутренне компилятор знает, что Diesel реализует интерфейс Engine , а затем может определить подходящий конструктор, выведя тип.
5. Заключение
Проще говоря, оператор diamond добавляет функцию вывода типов в компилятор и уменьшает многословие в назначениях, введенных с помощью универсальных методов.
Некоторые примеры этого руководства можно найти в проекте GitHub , поэтому не стесняйтесь загружать его и играть с ним.
Что такое даймонд оператор java
In this article, we’ll look at the diamond operator in Java and how generics and the Collections API influenced its evolution.
2. Raw Types
Prior to Java 1.5, the Collections API supported only raw types – there was no way for type arguments to be parameterized when constructing a collection:
This allowed any type to be added and led to potential casting exceptions at runtime.
3. Generics
In Java 1.5, Generics were introduced – which allowed us to parameterize the type arguments for classes, including those in the Collections API – when declaring and constructing objects:
At this point, we have to specify the parameterized type in the constructor, which can be somewhat unreadable:
The reason for this approach is that raw types still exist for the sake of backward compatibility, so the compiler needs to differentiate between these raw types and generics:
Even though the compiler still allows us to use raw types in the constructor, it will prompt us with a warning message:
The diamond operator – introduced in Java 1.7 – adds type inference and reduces the verbosity in the assignments – when using generics:
The Java 1.7 compiler’s type inference feature determines the most suitable constructor declaration that matches the invocation.
Consider the following interface and class hierarchy for working with vehicles and engines:
Let’s create a new instance of a Car using the diamond operator:
Internally, the compiler knows that Diesel implements the Engine interface and then is able to determine a suitable constructor by inferring the type.
5. Conclusion
Simply put, the diamond operator adds the type inference feature to the compiler and reduces the verbosity in the assignments introduced with generics.
Some examples of this tutorial can be found on the GitHub project, so feel free to download it and play with it.
1. Overview
In this article, we’ll look at the diamond operator in Java and how generics and the Collections API influenced its evolution.
2. Raw Types
Prior to Java 1.5, the Collections API supported only raw types – there was no way for type arguments to be parameterized when constructing a collection:
This allowed any type to be added and led to potential casting exceptions at runtime.
3. Generics
In Java 1.5, Generics were introduced – which allowed us to parameterize the type arguments for classes, including those in the Collections API – when declaring and constructing objects:
At this point, we have to specify the parameterized type in the constructor, which can be somewhat unreadable:
The reason for this approach is that raw types still exist for the sake of backward compatibility, so the compiler needs to differentiate between these raw types and generics:
Even though the compiler still allows us to use raw types in the constructor, it will prompt us with a warning message:
The diamond operator – introduced in Java 1.7 – adds type inference and reduces the verbosity in the assignments – when using generics:
The Java 1.7 compiler’s type inference feature determines the most suitable constructor declaration that matches the invocation.
Consider the following interface and class hierarchy for working with vehicles and engines:
Let’s create a new instance of a Car using the diamond operator:
Internally, the compiler knows that Diesel implements the Engine interface and then is able to determine a suitable constructor by inferring the type.
5. Conclusion
Simply put, the diamond operator adds the type inference feature to the compiler and reduces the verbosity in the assignments introduced with generics.
Some examples of this tutorial can be found on the GitHub project, so feel free to download it and play with it.
- Java
Core Java
Руководство по бриллиантовому оператору на Java
1. обзор
В этой статье мы рассмотримdiamond operator in Java and how generics and the Collections API influenced its evolution.
2. Сырые Типы
Prior to Java 1.5, the Collections API supported only raw types — не было возможности параметризации аргументов типа при создании коллекции:
Это позволило добавить любой тип иled to potential casting exceptions at runtime.
3. Дженерики
В Java 1.5 были введены Generics —which allowed us to parameterize the type arguments for classes, в том числе в API коллекций — при объявлении и построении объектов:
На этом этапе у нас естьspecify the parameterized type in the constructor, который может быть несколько нечитаемым:
Причина этого подхода в том, чтоraw types still exist for the sake of backward compatibility, поэтому компилятор должен различать эти необработанные типы и дженерики:
Хотя компилятор все еще позволяет нам использовать необработанные типы в конструкторе, он выдаст нам предупреждающее сообщение:
4. Алмазный Оператор
Оператор алмаза — введен в Java 1.7 —adds type inference and reduces the verbosity in the assignments – when using generics:
Функция вывода типа компилятора Java 1.7determines the most suitable constructor declaration that matches the invocation.
Рассмотрим следующий интерфейс и иерархию классов для работы с транспортными средствами и двигателями:
Давайте создадим новый экземплярCar с помощью оператора ромба:
Внутренне компилятор знает, чтоDiesel реализует интерфейсEngine, а затем может определить подходящий конструктор, определив его тип.
5. Заключение
Проще говоря, оператор diamond добавляет функцию вывода типов в компилятор и уменьшает многословность в присваиваниях, представленных с обобщениями.
Некоторые примеры этого руководства можно найти вon the GitHub project, так что не стесняйтесь загружать его и играть с ним.
is that on the left hand side, you are using the generic type List<String> where on the right side you are using the raw type LinkedList . Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless
you absolutely have to.
Now, if Java had generics from the beginning and didn’t have types, such as LinkedList , that were originally created before it had generics, it probably could have made it so that the constructor for a generic type automatically infers its type parameters from the left-hand side of the assignment if possible. But it didn’t, and it must treat raw types and generic types differently for backwards compatibility. That leaves them needing to make a slightly different, but equally convenient, way of declaring a new instance of a generic object without having to repeat its type parameters… the diamond operator.
As far as your original example of List<String> list = new LinkedList() , the compiler generates a warning for that assignment because it must. Consider this:
Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don’t get this protection and will get an error at runtime. This is why you should not use raw types.
The diamond operator, however, allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left side… without having to type those parameters again. It allows you to keep the safety of generics with almost the same effort as using the raw type.
I think the key thing to understand is that raw types (with no <> ) cannot be treated the same as generic types. When you declare a raw type, you get none of the benefits and type checking of generics. You also have to keep in mind that generics are a general purpose part of the Java language… they don’t just apply to the no-arg constructors of Collection s!
Автор оригинала: baeldung.
1. Обзор
В этой статье мы рассмотрим оператор diamond в Java и то, как generics и API коллекций повлияли на его эволюцию .
2. Необработанные Типы
До Java 1.5 API коллекций поддерживал только необработанные типы – при построении коллекции не было возможности параметризовать аргументы типа:
Это позволило добавить любой тип и привело к потенциальным исключениям приведения во время выполнения .
3. Дженерики
В Java 1.5 были введены дженерики– , которые позволили нам параметризовать аргументы типа для классов , в том числе в API коллекций – при объявлении и построении объектов:
На этом этапе мы должны указать параметризованный тип в конструкторе , который может быть несколько нечитаемым:
Причина такого подхода заключается в том , что необработанные типы все еще существуют для обеспечения обратной совместимости , поэтому компилятору необходимо различать эти необработанные типы и универсальные типы:
Несмотря на то, что компилятор по-прежнему позволяет нам использовать необработанные типы в конструкторе, он выдаст нам предупреждающее сообщение:
4. Алмазный оператор
Оператор diamond – введенный в Java 1.7 – добавляет вывод типов и уменьшает многословие в назначениях – при использовании дженериков :
Функция вывода типов компилятора Java 1.7 определяет наиболее подходящее объявление конструктора, соответствующее вызову .
Рассмотрим следующий интерфейс и иерархию классов для работы с транспортными средствами и двигателями:
Давайте создадим новый экземпляр Car с помощью оператора diamond:
Внутренне компилятор знает, что Diesel реализует интерфейс Engine , а затем может определить подходящий конструктор, выведя тип.
5. Заключение
Проще говоря, оператор diamond добавляет функцию вывода типов в компилятор и уменьшает многословие в назначениях, введенных с помощью универсальных методов.
Некоторые примеры этого руководства можно найти в проекте GitHub , поэтому не стесняйтесь загружать его и играть с ним.
Before Java 7, while using generics we had to supply type parameters to variable types and to their actual types. Now, it has been relieved a bit. And a blank Java diamond operator on the right side of the declaration will work fine.
The diamond operator is denoted with two angles ‘< >’ .
1. Raw Type Declarations (Prior to Java 1.5)
If you have worked on early versions of Java (before 1.5), when generics were not a Java feature, developers have to use raw types declarations and initializations. For example, given below is a HashMap declarations.
The problem with this approach is that you can put any object type in key and value, and only in runtime, we will get the error if the object is not of the desired type. There is no compile-time safety that can warn developers, which types are allowed and which are not.
2. Parameterized Types in Java 1.5
JDK 1.5 brought generics. It was a much-needed feature and completely changed the way developers write code. It enabled compile time safety. It helped in reducing runtime errors by a great number.
This syntax solves the problem of compile-time type safety. In fact, the above syntax is good for almost all use cases. In the above example, if you try to add any key or value of a different type, the compiler will give you an error.
You need to fix your code to get through the compiler.
3. Diamond Operator since Java 1.7
Parameterized types solved a few issues but seem heavy due to the same repeated type of information on both sides. We can reduce the syntax if we can provide type information on one side, and another side can detect and apply the type information.
The diamond operator in Java does exactly the same thing. It is also called Elvis operator. Look below at the diamond operator syntax.
In the above code, the compiler is smart enough to identify that the diamond operator infers to type defined on the left-hand side of the declaration. It applies the type information to the right side object as well. It helps in adding type inference features to Java.
4. Backward Compatibility
Raw types and parameterized types still exist for the sake of backward compatibility. But new compilers will warn if they see raw types. If you compile raw types with Java 5 onward, you will get a warning like this:
ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized.
Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.
Hello guys, if you are reading Java code and come across closed angle bracket with a diamond like shape and wondering what they are and what they do then you have come to the right place. They are known as Diamond operator in Java and I will explain you what they are and where should you use them in this article. The Diamond operator is a relatively new operator in Java which was first
introduced in
JDK 7 to improve type inference and reduce boilerplate Java coding. It is
denoted with a closed angle bracket that resembles the shape of a
diamond ( <> ) and that’s why it’s called the Diamond operator. If used correctly it
can reduce typing and boilerplate coding in Java and result in much cleaner
and readable code especially when you use Generics.
I regularly use the Diamond operator in Java while declaring and initializing
objects involving multiple
Generic types
like Map which holds another Map and because of improved type inference, I
only need to declare the type information on the left-hand side of declaration.
It reduces my typing by half, hence result in a faster coding
experience.
Before Java 6, generic type inference was poor in Java. You need to declare
type information on both the right and left-hand sides of the variable
declaration. This makes code unnecessary complicated, and hard to read,
especially when using nested types, like Map with Entry whose key is String
and value is
List of Integers.
By the way, if you’re new to the Java programming world then you can also join
the
best free Java programming courses
to kick start your Java developer journey. It’s my curated list and contains the
best free Java online courses from sites like Udemy, Pluralsight, Educative, and
Coursera to learn and level up Java skills for both beginners and intermediate
developers.
What is Diamond Operator Example in Java?
Here is how you can simplify code by using the diamond operator in Java;
remember, this feature is only available from Java SE 7 release, so you can
use it in JDK 7 and 8 but not in Java 6. If you want to improve type inference
in Java 6, take advantage of
static factory methods, as suggested by Joshua Bloch in his book Effective Java.

When to use Diamond Operator in Java?
Here are some examples of using the Diamond operator in Java. These are
the places where I found myself using diamond operator again and
again.
1. Reference variable Initialization
2. passing arguments to methods
when you call this method, you can use the Diamond operator as shown
below
Advantages of using Diamond Operator in Java
Here are some key advantages of using the Diamond operator in Java:
1. Less typing
2. Improved readability
3.
Concise code
Since all of these are related to improving code quality and developer productivity, I highly recommend Java developers both beginners and experienced one to start using diamond operator on the right hand side of assignment at least. It will not only save time and allow you to write code faster but also improve the readability of code.
That’s all about how to use the Diamond operator in Java. If
you are writing Java 7, then it’s always better to use the diamond
operator; there is no reason not to use it. You can always save few
keystrokes even if your type declaration is simple, but you will gain
more in the case of complex and nested type declarations. You can also
use the diamond operator while passing arguments to methods.
Other Core Java Articles and Tutorials you may like
- How to compare objects on multiple fields in Java (example)
- 20 Examples of Date and Time in Java 8 (tutorial)
- Top 5 Books to Learn Java 8 (read here)
- How to use Stream class in Java 8 (tutorial)
- How to convert List to Map in Java 8 (solution)
- How to use filter() method in Java 8 (tutorial)
- How to use forEach() method in Java 8 (example)
- How to use Stream API in Java 8 (learn here)
- How to implement Comparator using lambda expression (see here)
- How to filter Collection using Streams in Java 8 (check here)
- Understanding Default methods of Java 8 (learn here)
- How to join String in Java 8 (example)
- How to use peek() method in Java 8 (example)
- 8 Best Lambda and Functional Programming courses (best courses)
Thanks for reading this article so far. If you like this Java Diamond operator tutorials and examples then please share them with your friends and colleagues. If you have any questions or feedback about this Java 8 tutorial then please drop a note.