Skip to content

Instantly share code, notes, and snippets.

@mloza

mloza/LocalRecord.java

Last active Jan 19, 2020
Embed
What would you like to do?
Kod źródłowy do wpisu o Records Classes w Javie 14 znajdującego się pod adresem: https://blog.mloza.pl/java-14-record-classes/
public static void localRecord() {
String persons = """
Java,Developer,29
Python,Developer,25
John,Doe,65
""";
record LocalPerson(String firstName, String lastName, int age) {
LocalPerson(String[] data) {
this(data[0], data[1], Integer.parseInt(data[2]));
}
}
Arrays.stream(persons.split("\n"))
.map(i -> i.split(","))
.map(LocalPerson::new)
.forEach(System.out::println);
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Java", "Developer", 29);
System.out.println(p.firstName());
System.out.println(p.lastName());
System.out.println(p.age());
System.out.println(p);
}
}
public record Person(
String firstName,
String lastName,
int age) {}
public record Person (
String firstName,
String lastName,
int age) {
public Person {
if (age < 20) {
new IllegalArgumentException("You are too young!");
}
}
public Person() {
this("Java", "Developer", 21);
System.out.println("Default object has been created");
}
}
public record Person (
String firstName,
String lastName,
int age) {
public static int x;
public static int inc() {
return x++;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
public final class PersonOldWay {
private final String firstName;
private final String lastName;
private final int age;
public PersonOldWay(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String firstName() {
return firstName;
}
public String lastName() {
return lastName;
}
public int age() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PersonOldWay personOld = (PersonOldWay) o;
return age == personOld.age &&
Objects.equals(firstName, personOld.firstName) &&
Objects.equals(lastName, personOld.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("PersonOldWay{");
sb.append("firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", age=").append(age);
sb.append('}');
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.