Record
1. Record λ?
Record
λ λ¨μν λ°μ΄ν°λ₯Ό λ΄κΈ° μν ν΄λμ€λ₯Ό κ°λ¨ν μ μν μ μλλ‘ λμ
λ μλ‘μ΄ κ΅¬μ‘°
κΈ°μ‘΄μ 보μΌλ¬νλ μ΄νΈ μ½λ(μμ±μ, getter, equals, hashCode, toString λ±) λ₯Ό μλμΌλ‘ μμ±ν΄ μ£Όλ λ°μ΄ν° μ€μ¬ ν΄λμ€μ.
2. Record μ νΉμ§
1. κ°κ²°μ±
λ°μ΄ν°λ₯Ό μ μ₯νκΈ° μν΄ νμν μμ±μ,
getter
,equals
,hashCode
,toString
λ©μλκ° μλμΌλ‘ μμ±λ¨.κΈ°μ‘΄μ Java Bean μ€νμΌκ³Ό λ¬λ¦¬ 보μΌλ¬νλ μ΄νΈ μ½λλ₯Ό μμ±ν νμκ° μμ.
2. λΆλ³μ±
Record ν΄λμ€μ νλλ κΈ°λ³Έμ μΌλ‘
final
λ‘ μ μΈλ¨.setter λ©μλκ° μμΌλ©°, κ° λ³κ²½μ΄ λΆκ°λ₯ν¨.
3. λͺ©μ
μ£Όλ‘ λ°μ΄ν°λ₯Ό μ λ¬νκ±°λ μ μ₯ν μν μ©λλ‘ μ€κ³λμμ.
볡μ‘ν λΉμ¦λμ€ λ‘μ§μ ν¬ν¨νκΈ°μ μ ν©νμ§ μμ.
4. ν΄λμ€ μμ λΆκ°
Record λ μ묡μ μΌλ‘
final
λ‘ μ μΈλλ―λ‘ μμν μ μμ.
3. Record μ¬μ©λ²
기본 ꡬ쑰
Record ν΄λμ€λ₯Ό μ μνλ €λ©΄ record
ν€μλλ₯Ό μ¬μ©ν¨.
public record Person(String name, int age){}
2. Record μΈμ€ν΄μ€ μμ±
Person person = new Person("Alice", 25);
System.out.println(person.name()); // Alice
System.out.println(person.age()); // 25
3. μλ μμ± λ©μλ
Getter : νλλͺ μ λ©μλλ‘ μ¬μ©ν΄ κ°μ λ°ν
toString()
: νλ μ΄λ¦κ³Ό κ°μ ν¬ν¨ν λ¬Έμμ΄ μμ±equals()
: λ κ°μ²΄κ° λμΌν κ°μ κ°μ§λ©΄true
hashCode()
: κ°μ²΄λ₯Ό κ³ μ νκ² μλ³νλ ν΄μμ½λ
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Alice", 25);
System.out.println(person1); // Person[name=Alice, age=25]
System.out.println(person1.equals(person2)); // true
System.out.println(person1.hashCode()); // λμΌν ν΄μμ½λ λ°ν
4. Record μ μΆκ° κΈ°λ₯
1. 컀μ€ν
λ©μλ
Record
μλ 컀μ€ν
λ©μλλ₯Ό μΆκ°ν μ μμ.
public record Person(String name, int age){
public String greeting() {
return "Hello, my name is " + name + " and I am " + age + " years old.";
}
}
Person person = new Person("Alice", 25);
System.out.println(person.greeting()); // Hello, my name is Alice and I am 25 years old.
2. μμ±μ μ€λ²λΌμ΄λ©
Record λ μμΆλ Canonical Constructor λ₯Ό μλμΌλ‘ μμ±ν¨.
μμ±μλ₯Ό λͺ μμ μΌλ‘ μ μνκ±°λ, μ λ ₯κ°μ κ²μ¦ν μ μμ.
public record Person(String name, int age){
public Person{
if(age < 0) {
throw new IllegalArgumentException("Age must be non-negative");
}
}
}
5. Record μ μ μ½ μ¬ν
1. μμ λΆκ°
Record λ μ묡μ μΌλ‘
final
λ‘ μ μΈλλ―λ‘ μμν μ μμ.λμ μΈν°νμ΄μ€λ₯Ό ꡬνν μ μμ.
public record Person(String name, int age) implements Comparable<Person> {
@Override
public int compareTo(Person other){
return this.name.comapreTo(other.name);
}
}
2. κ°λ³ νλ μ¬μ© λΆκ°
νλλ λ°λμ
final
μ΄μ΄μΌ νλ©°, κ°λ³ λ°μ΄ν°λ₯Ό ν¬ν¨ν μ μμ.λ°°μ΄ κ°μ κ²½μ°, νλκ°
final
μ΄μ§λ§ λ΄λΆ κ°μ λ³κ²½ κ°λ₯ν¨.
public record DataHolder(int[] data){}
DataHolder holder = new DataHolder(new int[]{1,2,3});
holder.data()[0] = 42; // λ΄λΆ λ°μ΄ν° λ³κ²½ κ°λ₯
3. 볡μ‘ν λ‘μ§ ν¬ν¨ λΆκ°
Record λ κ°λ¨ν λ°μ΄ν° μ μ₯μ©λλ‘ μ€κ³λμμΌλ―λ‘ λ³΅μ‘ν λΉμ¦λμ€ λ‘μ§μλ μ ν©νμ§ μμ.
Last updated
Was this helpful?