☕️ 김영한의 실전 자바 - 중급 1편 을 수강하며 학습한 내용을 저만의 언어로 정리하고 있습니다.
java.util
패키지는 컬렉션 프레임워크, 날짜와 시간 관련 기능 등 유용한 클래스들이 포함되어 있는 패키지이다.
그 중 Random
클래스는 난수 생성 기능을 제공하는 클래스이다.
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
int randomInt = random.nextInt();
double randomDouble = random.nextDouble();
boolean randomBoolean = random.nextBoolean();
System.out.println("randomInt = " + randomInt);
// 1에서 5 사이의 random한 정수형 얻기
int randomInt1_5 = random.nextInt(5) + 1;
System.out.println("randomInt1_5 = " + randomInt1_5);
}
}
Random 인스턴스를 생성한다.
.nextInt()
메서드로 int
형 난수를 반환한다.
nextLong(), nextFloat(), nextBoolean(), nextDouble()
등 가능.nextInt(int bound)
메서드는 0 이상 bound 미만의 int형 난수를 반환한다.
random.nextInt(5) + 1
와 같이 코드를 작성한다.Random.nextInt()
의 내부를 살펴보자.
내부에서
this.seed
라는 값을 이용해서 정수값을 만들고 있다.
1. public Random()
new Random()
으로 객체를 생성하는 경우System.nanoTime()
에 알고리즘을 조합해서 랜덤한 seed값을 생성한다.2. public Random(long seed)
예시 코드
public class RandomExample {
public static void main(String[] args) {
Random randomSeed = new Random();
int fromRandomSeed = randomSeed.nextInt();
System.out.println("fromRandomSeed = " + fromRandomSeed);
Random knownSeed = new Random(10);
int fromKnownSeed1 = knownSeed.nextInt();
int fromKnownSeed2 = knownSeed.nextInt();
System.out.println("fromKnownSeed1 = " + fromKnownSeed1);
System.out.println("fromKnownSeed2 = " + fromKnownSeed2);
}
}
fromRandomSeed
의 값은 코드를 실행할 때마다 랜덤하게 바뀐다.fromKnownSeed1
은 항상 -1157793070, fromKnownSeed2
는 항상 1913984760이 할당된다.마인크래프트의 지형 요소, 아이템 드랍 등을 결정하는 값을 Seed라고 한다.
마인크래프트 세계를 만들 때 이를 지정하지 않으면 무작위로 Seed가 생성된다.
내가 플레이하고 싶은 세계가 있을 때, 버전이 같다는 가정 하에 같은 Seed를 입력하면 동일한 세계에서 플레이 하는 것이 가능하다.