Computer Science/Java
[Java] 자바 코드 관련 팁 (삼항 연산자, break Label, TreeSet, Stack, Queue)
⛅
2021. 8. 18. 14:41
삼항 연산자
자바에서 삼항 연산자를 사용하면 조건문을 더 간단히 표현할 수 있다.
삼항 연산자의 예시는 다음과 같다.
public class Test
public static void main(String[] args) {
int num=8;
String result = (num>10) ? "bigger than 10" : "smaller than 10";
System.out.println(result) // smaller than 10
}
}
break Label
중첩 for 문이 사용되었을 때 break Label을 사용하면 외부 for문 밖으로 나갈 수 있다.
public class Test
public static void main(String[] args) {
Flag: for(int i=0; i<10; i++){
for(int j=10; j<15; j++){
System.out.println(j);
if(j==12){
break Flag;
}
}
}
}
}
/*
10
11
12
*/
TreeSet과 TreeMap
TreeSet과 TreeMap은 각각 binary tree를 기반으로 한 순서가 있는 set과 map으로, 검색을 할 때 유용하게 사용할 수 있는 자료구조이다.
public class Test
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<Integer>();
set.add(5);
set.add(2);
set.add(3);
Ssytem.out.println(set.first()); // 2
Ssytem.out.println(set.lower(4)); // 3
}
}
Stack과 Queue
자바에서도 Stack과 Queue 자료구조를 사용할 수 있다. Stack은 Last In First Out (마지막에 넣은 것이 가장 먼저 나감)이고, Queue는 First In First Out (처음 넣은 것이 가장 먼저 나감)이다.
public class Test
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // 2
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(1);
queue.offer(2);
System.out.println(queue.poll()); // 1
}
}
Reference
- 이것이 자바다
728x90
반응형