Java 정리 19
07 Dec 2018
Reading time ~4 minutes
Java 정리 19 - Set, Map, AWT, 배치관리자
Set
-
중복값을 저장하지 않는다.
- 값을 유일하게 관리
- 값이 순차적으로 추가되지 않는다.
- 값의 검색이 되지 않는다.(get메소드가 없다)
- Iterator를 사용
- 구현된 HashSet 사용
// 1.생성) jdk 1.5이전에서는 Generic 사용불가, 객체만 넣는다
Set set = new HashSet(); // jdk 1.5이전
Set<E> set = new HashSet<>(); // jdk 1.5+
// 2. 값 할당) 값이 객체면 그냥 입력, 기본형 데이터형인 경우 autoboxing 된다.
// autoboxing - wrapper class를 사용하여 객체가 만들어지고 입력되는 것
set.add(값);
// 3. 방의 개수)
set.size();
// 4. 방의 값 삭제) set은 순차적으로 입력되지 않으므로 index로 삭제불가, 값으로만 삭제
set.remove(값);
// 5. 조회할 수 없다!(검색 안됨), Iterator를 사용, 제어권을 넘겨준다
Iterator<E> ita = set.iterator(); // set의 제어권(포인터)을 받아옴
while(ita.hasNext()) {
System.out.println(ita.next());
}
// Set을 사용해서 로또 중복번호 제거하기
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class LottoUsingSet {
public int[] lotto() {
int[] tempLotto = new int[6];
Random random = new Random();
for(int i=0; i<tempLotto.length; i++) {
// 같은 수가 발생가능
tempLotto[i] = random.nextInt(45)+1;
for(int j=0; j<i; j++) {
if(tempLotto[i] == tempLotto[j]) {
// 중복발생된 번호의 인덱스 번호를
// 다시 발생시키기 위해 인덱스 번호를 하나 줄인다.
i--;
break;
}
}
}
return tempLotto;
}
public Integer[] lottoUsingSet() {
Integer[] tempLotto = new Integer[6];
Set<Integer> set = new HashSet<Integer>();
Random random = new Random();
while(true) {
// 같은수가 추가되지 않음
set.add(random.nextInt(45)+1);
if(set.size() == 6) break;
}
set.toArray(tempLotto);
return tempLotto;
}
public static void main(String[] args) {
LottoUsingSet lus = new LottoUsingSet();
int[] temp = lus.lotto();
for(int i=0; i<temp.length; i++) {
System.out.print(temp[i]+" ");
}
System.out.println("\n------------------");
Integer[] temp1 = lus.lottoUsingSet();
for(int i=0; i<temp1.length; i++) {
System.out.print(temp1[i]+" ");
}
}
}
Map
-
키와 값의 쌍(KVP, Key Value Pair, entry)으로 이루어진 데이터형
- 2차원 배열처럼 생성(행, 열)
- 열은 2개(K,V)만 존재
- 가변길이형
-
키는 중복될 수 없다.
- 식별가능해야 하기 때문에 유일해야 함
- 값은 중복값을 가질 수 있다.
- 키를 사용하여 값을 얻는다.
- 구현된 Hashtable, HashMap
- 생성자 오버로드로 행의 수를 넣을 수 있다.
- 전체행의 약 75%의 데이터가 존재할 때 가장 빠른 검색을 수행
- Hashtable은 멀티쓰레드에서 동시접근이 안된다.(동기화 O, 16개의 행 생성)
- HashtMap은 멀티쓰레드에서 동시접근이 가능.(동기화 X, 11개의 행 생성)
// 1.생성)
Map<K,V> map = new HashMap<K,V>();
= new Hashtable<K,V>();
// 2.값추가) - autoboxing
map.put(키, 값);
// 3.행의 개수)
map.size();
// 4.값얻기) - unboxing
map.get(키);
// 5.삭제)
map.remove(키);
// 6.모든 키 얻기) map 검증
map.keySet();
// 7.키가 존재하는지 확인)
map.containsKey(키);
JFC (Java Foundation Classes)
- Windows용 Application을 작성할 수 있게 제공하는 클래스들
- AWT(Abstract Window Toolkit), Swing 제공
- 사용자의 행동에 따른 동작은 Event Handling으로 처리한다.
- exe파일이 생성되지 않는다.
AWT (Abstract Window Toolkit)
- java.awt 패키지에서 관련 클래스 제공
-
Component Programming
- Component : 기능을 가질 수 있는 최소한의 단위로 만들어진 디자인 클래스들
- 무겁다(=느리다), 버그가 많다, 미려하지않은 디자인, 이미지 다루기가 어려움
- 익히긴 쉽다
-
JVM는 컴포넌트의 기능만 알고 있다.
- 디자인은 OS에서 가져다가 사용 (OS마다 디자인이 다르게 그려진다)
- 그래픽성능이 매우 떨어진다.
-
Component의 종류
-
눈에 보이지 않는 Component(Non Visual Component)
- Font, Color, CheckboxGroup
-
눈에 보이는 Component(Visual Component)
-
Window Component : 사용자에게 보여주는 기능
- Window, Frame, Dialog, FileDialog
-
Container Component : Component를 저장하고 배치하는 기능
- Panel, ScrollPane
-
Component : 기능을 가진 최소단위
- Label, Button, Checkbox, TextField, TextArea, List, Choice
-
Window Component : 사용자에게 보여주는 기능
-
눈에 보이지 않는 Component(Non Visual Component)
- 작성법
- Window Component를 상속
- 사용자에게 제공할 일반컴포넌트를 생성
- 배치관리자(LayoutManager)를 사용하여 컴포넌트 배치
- 윈도우 크기 설정
- 사용자에게 보여주기
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Window Application 작성
*/
// 1. Window Component 상속
@SuppressWarnings("serial")
public class HelloAwt extends Frame {
public HelloAwt() {
super("Awt 연습"); // Frame 인자생성자 호출(타이틀설정)
// 2. 사용할 일반컴포넌트 생성.
Label lblTitle = new Label("오늘 베스트 사자성어", Label.CENTER);
TextArea ta = new TextArea("정택성씨\n구로1동의 자랑");
// 3. 배치관리자를 사용하여 컴포넌트를 배치
add("North",lblTitle);
add("Center",ta);
// 4. 윈도우의 크기를 설정
setSize(400, 270);
// 5. 사용자에게 보여주기
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// 현재 윈도우인스턴스만 종료
dispose();
}
});
}
public static void main(String[] args) {
new HelloAwt();
}
}
배치관리자
- Window Component와 Container Component가 배치하는 위치를 설정해 놓은 것
-
자동배치, 수동배치 두가지를 사용
-
자동배치
- BorderLayout, FlowLayout, GridLayout, GridBagLayout, CardLayout
- 배치가 편리하지만 세밀한 디자인은 어렵다.
- 수동배치는 개발자가 좌표를 직접 입력해서 배치
-
자동배치
- Frame은 BorderLayout이 기본 Layout
- Panel은 FlowLayout이 기본 Layout
// 적용
setLayout(new LayoutManager());
-
BorderLayout (경계레이아웃)
- Frame의 기본 Layout.
- 지역으로 구분
- 하나의 지역에는 하나의 Component만 배치된다.
-
배치되는 컴포넌트는 고유 크기가 무시되고 지역의 크기만큼 커진다.
- Center Component 크기가 가장 크다
setLayout(new BorderLayout());
add("영역", 배치할컴포넌트);
// 영역은 BorderLayout 필드를 사용해도 됨
// CENTER, EAST, NORTH, SOUTH, WEST
-
FlowLayout (흐름 레이아웃)
- Panel의 기본 Layout
- 컴포넌트가 고유 크기를 가지면서 순서대로 배치된다.
- 윈도우의 크기가 변경되면 컴포넌트의 위치가 변경된다.
setLayout(new FlowLayout());
-
CardLayout
-
한정적인 공간에서 여러디자인을 번갈아가면서 보여줄 때 사용
- 이클립스 탭
- Container Component에만 적용 가능
-
한정적인 공간에서 여러디자인을 번갈아가면서 보여줄 때 사용
// 패널객체엔 Event가 들어가 있어야 번갈아가면서 다른 화면을 보여줄 수 있음.
패널객체.setLayout(new CardLayout());