Java14 came out, so I tried record for the time being

Overview

Java 14 is out. There are various changes and new features, but what you are interested in is the record that was included as a preview, right? Right? That's why I tried it immediately.

important point

record is a feature included as a preview, so you need to use magic to use it.

java --enable-preview --source 14 RecordSample.java

Also, the content written here is subject to change in the future. (Because it's a preview)

Contents

Basic usage of record

If you use record, a method (getter) to get the field specified at the time of definition is automatically generated.

public class RecordSample {
    public static void main(String[] args) {
        var person = new Person("Mario", 26);

        System.out.println(person.name());    // Mario
        System.out.println(person.age());     // 26
    }
}

//definition of record
record Person(String name, int age) {}

The point is that the definition of record is very simple. Also, the code on the side that uses record can be written exactly like a conventional class. Also, getters are methods with the same name as fields, not getName (). The setter is not generated. I think it would be nice to be able to choose whether to generate a setter as well, but in general it's better for the object to be immutable, so this may be fine.

Also, using record automatically overrides toString (), equals (), and hashCode () defined in the Object class. Let's look at each example.

Example of toString ()

public class ToStringSample {
    public static void main(String[] args) {
        var person = new Person("Mario", 26);

        System.out.println(person.toString());     // Person[name=Mario, age=26]
    }
}

//definition of record
record Person(String name, int age) {}

it is a good feeling. You won't use it directly, but it's useful when debugging.

Example of equals ()

public class EqualsSample {
    public static void main(String[] args) {
        var person1 = new Person("Mario", 26);
        var person2 = new Person("Mario", 26);

        System.out.println(person1.equals(person2));  // true

        person1 = new Person("Mario1", 26);
        person2 = new Person("Mario2", 26);

        System.out.println(person1.equals(person2));  // false

        person1 = new Person("Mario", 26);
        person2 = new Person("Mario", 27);

        System.out.println(person1.equals(person2));  // false
    }
}

//definition of record
record Person(String name, int age) {}

It is true when comparing different objects with the same value (top example), so you can see that they are comparing the field values properly, not the original behavior of the Object class. I've tried different values for specific fields, but of course it's false.

hashCode () example

public class HashCodeSample {
    public static void main(String[] args) {
        var person1 = new Person("Mario", 26);
        var person2 = new Person("Mario", 26);

        System.out.println(person1.hashCode());  // -1997440586
        System.out.println(person2.hashCode());  // -1997440586
    }
}

//definition of record
record Person(String name, int age) {}

This is also the same value for another object with the same value. It has been overridden properly.

Constructor example

public class ConstructorSample {
    public static void main(String[] args) {
        new Person("Mario", -1);
        // Exception in thread "main" java.lang.IllegalArgumentException
        // at Person.<init>(ConstructorSample.java:11)
        // at ConstructorSample.main(ConstructorSample.java:3)
    }
}

//definition of record
record Person(String name, int age) {
    public Person {
        if(age < 0) {
            throw new IllegalArgumentException();
        }
    }
}

It seems that you can also define a constructor. You don't have parentheses. Well, when it comes to writing arguments, you have to write exactly the same thing as above, but if there are parentheses without arguments, it looks like there is an argumentless constructor, so notation without parentheses Probably became. I think it's good. Also, if the access modifier is not public, a compile error will occur.

Example of defining another field or method

public class OtherMemberSample {
    public static void main(String[] args) {
        var person = new Person("Mario", 26);
        System.out.println(person.getGender());  // male
    }
}

//definition of record
record Person(String name, int age) {
    private static String gender = "male";

    public String getGender() {
        return gender;
    }
}

I don't know if I ever want to do that, but I've tried defining other fields and methods. It seems that the field must be static, but it seems that it can be done.

An example of explicitly defining a method that is automatically overridden

public class ExplicitOverrideSample {
    public static void main(String[] args) {
        var person = new Person("Mario", 26);
        System.out.println(person.toString());      // overrided

        System.out.println(person.equals(person));  // false

        System.out.println(person.hashCode());      // -1
    }
}

//definition of record
record Person(String name, int age) {
    @Override
    public String toString() {
        return "overrided";
    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        return -1;
    }
}

This is also an example of who does such a thing, but I tried it. Apparently it is more effective to write it explicitly.

Impressions

Please become a formal function as soon as possible.

Reference link

Recommended Posts

Java14 came out, so I tried record for the time being
Java12 came out, so I tried the switch expression for the time being
I tried using Docker for the first time
I tried touching Docker for the first time
Use Java external library for the time being
Run Dataflow, Java, streaming for the time being
The training for newcomers was "Make an app!", So I made an app for the time being.
I want you to use Scala as Better Java for the time being
[Rails] I tried using the button_to method for the first time
I tried the Java framework "Quarkus"
Introduction to java for the first time # 2
I tried Cassandra's Object Mapper for Java
Java9 was included, so I tried jshell.
I tried the new era in Java
Learning for the first time java [Introduction]
For the time being, run the war file delivered in Java with Docker
Glassfish tuning list that I want to keep for the time being
[First Java] Make something that works with Intellij for the time being
Install Amazon Corretto (preview) for the time being
[Deep Learning from scratch] in Java 1. For the time being, differentiation and partial differentiation
Since the docker-desktop preview for m1 came out, I tried to face it with my macbook pro 15inch
I tried using the Migration Toolkit for Application Binaries
Learn for the first time java # 3 expressions and operators
Try running Spring Cloud Config for the time being
I tried using an extended for statement in Java
Learning memo when learning Java for the first time (personal learning memo)
I tried to implement the Euclidean algorithm in Java
Command to try using Docker for the time being
I tried to find out what changed in Java 9
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
Access Web API on Android with Get and process Json (Java for the time being)
I translated [Clone method for Java arrays] as the Clone method in Java arrays.
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
Hello World with Ruby extension library for the time being
Java SE 13 (JSR388) has been released so I tried it
I tried using the CameraX library with Android Java Fragment
I tried Drools (Java, InputStream)
I tried the Docker tutorial!
I tried the VueJS tutorial!
I tried using Java REPL
I tried the FizzBuzz problem
[Java] I implemented the combination.
I studied the constructor (java)
I tried metaprogramming in Java
[Memo] Run Node.js v4.4.5 on CentOS 4.9 / RHEL4 (i386) for the time being (gcc-4.8 and glibc2.11 on LinuxKernel 2.6.9)
[Learning record] I got the current time in Ruby and output a different greeting for each time.
[Metal] I tried to figure out the flow until rendering using Metal
I passed the Java test level 2 so I will leave a note
I tried the input / output type of Java Lambda ~ Map edition ~
I tried to translate the error message when executing Eclipse (Java)
I tried to summarize the methods of Java String and StringBuilder
[Java] I tried to make a maze by the digging method ♪
I tried to move the Java compatible FaaS form "Fn Project"
I passed the Oracle Java Bronze, so I summarized the outline of the exam.
I tried to display the calendar on the Eclipse console using Java.
Spring Boot for the first time
I tried to interact with Java
I tried UDP communication with Java
I tried to explain the method