Written by coh at home
[Java] 입출력과 최대힙 본문
java로 코테를 준비하게 되었다.
1. 입출력
Scanner sc = new Scanner(System.in);
가장 기본적인 입력받는 객체.
버퍼에 개행이 남아있는 것을 주의 해야한다.
1
12345
sc.nextInt(); // 1
sc.nextLine(); // \n
sc.nextLine(); // 12345BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
입력이 빠르다.
이 경우 throws IOException을 붙여줘야 한다.
StringBuilder sb = new StringBuilder();
sb.append();
출력에서 빠른 성능을 보장해준다. 음.. 문자열 객체인 String을 이어 붙일 때 새로운 객체를 만들지만 StringBuilder는 하나의 객체에 요소를 추가함으로서 성능적인 이점을 얻을 수 있기 때문이다.
2. 최대힙 & Comparable
간단한 예시..
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // minHeap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); //maxHeap
runHeap(minHeap); // 1 2 3 5 8
runHeap(maxHeap); // 8 5 3 2 1
private void runHeap(PriorityQueue<Integer> heap){
heap.add(1);
heap.add(8);
heap.add(5);
heap.add(2);
heap.add(3);
while(!heap.isEmpty())
sout(heap.poll());
}보통 문제는 여러 개의 값을 비교하고 최대 최소를 구하라고 합니다. 이를 위해서는 객체를 생성하고 해당 객체의 Comparable을 처리하는 것이 좋습니다.
public class Person implements Comparable<Person>{
int grade;
int age;
@Override
public String toString(){
return "(grade, age) :" + grade "," + age;
}
@Override
public int compareTo(Person target){
if (this.grade == target.grade)
this.age <= target.age ? -1 : 1;
else
this.grade <= target.grade ? -1 : 1;
}
}
private void runHeap(PriorityQueue<Integer> heap){
heap.add(new Person(1, 5));
heap.add(new Person(1, 4));
heap.add(new Person(2,5));
heap.add(new Person(4,3));
heap.add(new Person(4,5));
while(!heap.isEmpty())
sout(heap.poll());
}꿀팁
import java.util.*;하고 시작하자.
'languages > java' 카테고리의 다른 글
| [Stream] mapToInt vs map (0) | 2024.10.07 |
|---|---|
| Collections vs Collectors (0) | 2024.10.05 |
| [JAVA] 제네릭의 언박싱을 탐구해보자 (0) | 2024.08.04 |
| [JAVA] 함수형 인터페이스와 스트림. (0) | 2024.02.02 |
| [JAVA]상속과 다형성 (1) | 2023.10.30 |