Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the diamond operator in Java? [duplicate]

I have an arraylist with type patient_class and the arraylist type has been underlined in yellow and the IDE has mentioned "redundant type arguments in new expression (use diamond operator instead)".

My problem is: Should I use the diamond operator instead? Is it a must? Will I get any data loss or any other problem when storing records to the arraylist?

Here is my arraylist:

public class Register_newpatient extends javax.swing.JFrame {

    public Register_newpatient() {
        initComponents();
        groupbutton();
    }

    public void groupbutton()
    {
        ButtonGroup bg1=new ButtonGroup();

        bg1.add(rbopd);
        bg1.add(rbinpatientcare);
        bg1.add(rbboth);
    }

    all_error_handling checkerror = new all_error_handling();
    JFrame frame = new JFrame();
    static ArrayList<patient_class>patientlist = new ArrayList<patient_class>();

To be honest I have no idea what a diamond operator actually is.

like image 765
Troller Avatar asked May 03 '13 06:05

Troller


People also ask

What is diamond operator in Java?

The diamond operator – introduced in Java 1.7 – adds type inference and reduces the verbosity in the assignments – when using generics: List<String> cars = new ArrayList<>(); The Java 1.7 compiler's type inference feature determines the most suitable constructor declaration that matches the invocation.

What are generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

What is generics in Java What are advantages of using generics?

Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically.


2 Answers

Don't worry. It's not an evil. It's feature of Java 7.

The purpose of the diamond operator is to simplify instantiation of generic classes.

For example, instead of

List<Map<Integer,Set<String>>> p = new ArrayList<Map<Integer,Set<String>>>();

with the diamond operator we can write only

List<Map<Integer,Set<String>>> p = new ArrayList<>();

If you want to know more about it and want to use it, please have a quick look here and decide whether it's useful to you or not.

like image 88
Suresh Atta Avatar answered Sep 17 '22 17:09

Suresh Atta


The diamond operator is used to specify what type of data you are going to use in the Collections.

For example, ArrayList<String> list = new ArrayList<String>().

In Java 7, we can eliminate the type like:

ArrayList<String> list = new ArrayList<>()
like image 24
prasanth Avatar answered Sep 21 '22 17:09

prasanth