1. HashMap은 어떤 순서도 유지하지 않습니다.

즉, HashMap 은 최초로 삽인된 요소가 최초로 인쇄되는 것을 보증하지 않습니다.

TreeSet와 같이, Treemap요소도 요소의 자연순서 부에 따라 소트됩니다.

 

2. 내부 HashMap구현은 Hashing을 사용하고 TreeMap은 Red-black트리 구현을 내부적으로 사용합니다.

 

3. HashMap은 하나의 nulll키와 많은 null values를 저장할수 있습니다.

  TreeMap은 Null키를 포함할수 없지만 많은  null값을 포함할 수 있습니다.

 

4. HashMap은 O(1)과 같은 get과 put 같은 기본 연산에 대해 일정한 시간 성능을 나타냅니다.

오라클 문서에 따르면  TreeMap은 get 및 put 메소드에 대한 log(n) 시간 보장 비용을 제공합니다.

 

5. HashMap의 성능 시간은 대부분의 작업에서 TreeMap에 대해 일정하므로 HashMap은 TreeMap보다 훨씬 빠릅니다.

 

6. HashMap은 비교해서 equals() 메소드를 사용하지만

TreeMap은 ordering 을 유지하기 위해 compareTo() 메소드를 사용합니다..

 

7. HashMap은 Map 인터페이스를 구현하고 TreeMap은 NavigableMap인터페이스를 구현합니다.

 

'Java' 카테고리의 다른 글

HashSet  (0) 2019.11.07
HashMap  (0) 2019.11.04
Java Tip&Tech : 배열 복사하기 -System클래스 이용하는 방법  (0) 2019.09.26
Java Tip&Tech : 인터페이스와 추상클래스의 차이점  (0) 2019.09.24
Java Day 14 : Thread  (0) 2019.06.14

 

 

/*
1.HashMap이란?
HashMap은  Map을 구현한다. Key와 Value를 묶어 하나의 entry로 저장한다는 특징 
hashing을 사용하기 때문에 많은 양의 데이터를 검색하는데 뛰어난 성능을 보인다.
- Map 인터페이스의 한 종류로 ("key",value)로 이루어짐
- key값을 중복이 불가능하고 value는 중복이 가능.value에 null값도 사용가능
- 멀티쓰레드에서 동시에 HashMap을 건드려 key-value값을 사용하면 문제가 될 수 있음.멀티쓰레드에서는  HashTable쓴다.

2.HashMap 생성자/메서드
* HashMap() -HashMap 객체를 생성
ex) 
HashMap<String,Integer>map = new HashMap<String,Integer>();
Map<String,Integer>map = new HashMap<String,integer>();

void.clear() - HashMap에 저장된 모든 객체를 제거 ex)map.clear();

* Object clone() 
- 현재 HashMap을 복제하여 반환한다. 
ex) newmap = (HashMap)map.clone();

* boolean containsKey(object Key) - HashMap에 저장된 키(key)가 포함되어 있는지 알려준다.
* boolean containsValue(object Value) - HashMap에 저장된 키(Value)가 포함되어 있는지 알려준다.

* Set entrySet()
- HashMap에 저장된 Key-Value값을 엔트리(키와 값을 결합)의 형태로 Set에 저장하여 반환한다
ex) map.put("A",1);
map.put("B",2);
Set set = map.entrySet();
System.out.println("set Values are" + set);
(result) set values : [A=1,B=2]

* Object get(Object key)
- 지정된 Key의 값을 반환한다. 

* bloolean isEmpty 
- HashMap이 비어있는지 확인한다.
bloolean val = map.isEmpty();

* Set keySet() 
- HashMap에 저장된 모든 키가 저장된 Set을 반환

* void putAll(Map m) 
Map에 해당하는 모든 요소를  HashMap에 저장한다.

* Object remove(Object Key)
- HashMap에 저장된 키로 지정된 값을 제거 

* Collection values() 
-HashMap에 저장된 모든 값을 컬렉션 형태로 반환한다.

 */

어떤 배열의 부분을 다른 배열로 복사하는 방법 

1. for문을 이용하여 배열의 각 오브젝트를 복사하는 방법

2.System클래스 이용하는 방법

System 클래스의 arratcopy 메소드는 자바 언어에서 자체적으로 지원하는 배열복사메소드

arratcopy 메소드의 입력값은 복사하려는 배열, 복사하려는 배열의 시작위치, 저장될 배열, 저장될 배열의 저장 위치, 복사할 배열 크기이며 한가지 알아둘 사항은 복하할 배열의크기가 저장될 배열의 크기보다 크면 ArratIndexOutOfBoundsException오류가 나므로 저장될 배열의 크기 더 늘려줘야함 

'Java' 카테고리의 다른 글

HashSet  (0) 2019.11.07
HashMap  (0) 2019.11.04
Java Tip&Tech : 인터페이스와 추상클래스의 차이점  (0) 2019.09.24
Java Day 14 : Thread  (0) 2019.06.14
Java Day13: ArrayList,Map,Generic,Excepction  (0) 2019.06.14

인터페이스와 추상클래스 :  구현 혹은 상속하는 클래스가 해당 기능을 완성하여 클래스를 만드는 기능

인터페이스 + : 추상클래스와 다르게 여러개의 인터페이스를 구현할수 있음

// 자바에서 다중상속을 허용하지 않기 때문에  다중상속을 우회적으로 구현할 수 있도록 해준다.

 

<Thread>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.day14;
//Thread(스레드) : 분신의 개념(멀티태스킹 수행)    
//스레드 작업시 절대 중복되서 작업 하지 않음!!
class MyThread1 extends Thread{
    
    private int num;
    private String name;
    
    public MyThread1(int num, String name){
        this.num = num;
        this.name = name;
    }
    @Override
    public void run() { //스레드의 메소드
        
        int i = 0;
        
        while(i<num){
            
            System.out.println(this.getName()+ " : " + name + i);
            i++;
            
            try {
                
                sleep(100);//특정 메소드가 0.1초 만큼 쉬는 시간을 줌    //1000이 1초의 시간
                //첫번째가 돌아가다 쉬는 시간에 두번째가 돌아가는 모습
                
            } catch (Exception e) {
                // TODO: handle exception
            }
            
        }
        
    }
    
}
public class Test1 {
    public static void main(String[] args) {
        
        System.out.println("main 시작....");
        
        MyThread1 t1 = new MyThread1(100"첫번째 : ");
        MyThread1 t2 = new MyThread1(200"두번째 : ");
        
        t1.start();    //스레드 호출(run()메소드 호출)
        try {
            t1.join();
        } catch (Exception e) {
            // TODO: handle exception
        }
        t2.start();
        
        System.out.println("main 종료....");    //main이 종료되어도 스레드는 종료될때까지 진행
        
    }
}
 
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.day14;
 
class MyThread2 implements Runnable{
 
    private int num;
    private String name;
    
    public MyThread2(int num, String name){
        
        this.num = num;
        this.name = name;
                
    }
        
    @Override
    public void run() {
        
        int i=0;
        
        while(i<num){
            
            System.out.println(name + " : " + i);
            i++;
            
            try {
                
                Thread.sleep(100);    //Runnable은 sleep 앞에 Thread를 붙여줘야 함.
                
            } catch (Exception e) {
                // TODO: handle exception
            }
                        
        }        
        
    }        
    
}
 
public class Test2 {
 
    public static void main(String[] args) {
        
        System.out.println("main 시작....");
        
        Thread t1 = new Thread(new MyThread2(100"첫번째"));
        Thread t2 = new Thread(new MyThread2(200"두번째"));
        
        //실행순서는 CPU가 조정
        
        t1.start();    //스레드 호출(run()메소드 호출)
        t2.start();
        
        //스레드 3개 실행(main, t1.start, t2start)
        
        System.out.println("main 종료....");
 
    }
 
}
cs

==Console===

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.day14;
 
 
class TClock implements Runnable{
 
    @Override
    public void run() {
            
        while(true){
            
            System.out.printf("%1$tF %1$tT\n",Calendar.getInstance());
            
            try {
                
                Thread.sleep(1000);
                
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
}
 
public class Test3 {
 
    public static void main(String[] args) {//mainThread
 
        //System.out.printf("%1$tF %1$tT\n",Calendar.getInstance());    //1$ f절 뒤에 것을 하나만 써서 중복 사용
        
        Thread tc = new Thread(new TClock());
        
        tc.start();
        
    }
 
}
 
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.day14;
 
//스레드 우선순위
 
class MyThread4 extends Thread{
    
    private String name;
    
    public MyThread4(String name){
        
        this.name = name;
        
    }
 
    @Override
    public void run() {
        
        for(int i = 1;i<=20;i++){
            
            System.out.println(name + " : " + i);
            
        }
    }
    
}
 
public class Test4 {
 
    public static void main(String[] args) {
        
        MyThread4 ob1 = new MyThread4("A");
        MyThread4 ob2 = new MyThread4("B");
        MyThread4 ob3 = new MyThread4("C");
        
        //우선순위 종류    //확인하는 방법
        System.out.println("MIN : " + Thread.MIN_PRIORITY);//1
        System.out.println("NORM : " + Thread.NORM_PRIORITY);//5    //보통 Thread의 우선순위 
        System.out.println("MAX : " + Thread.MAX_PRIORITY);//10
        
        //스레드 기본 우선순위
        System.out.println(ob1.getPriority());//5
        System.out.println(ob2.getPriority());//5
        System.out.println(ob3.getPriority());//5
        
        //우선순위를 변경
        //ob1.setPriority(1); 을 줘도 가능함(가로 안에 1~10 사이의 값으로 조정함)
        ob1.setPriority(Thread.MIN_PRIORITY);//1
        ob2.setPriority(Thread.NORM_PRIORITY);//5
        ob3.setPriority(Thread.MAX_PRIORITY);//10
        
        ob1.start();
        ob2.start();
        ob3.start();
        
    }
 
}
 
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.day14;
 
//Daemon 스레드
//다른 스레드에 도움을 주는 스레드로 다른 스레드가 종료되면 데몬 스레드가 종료되지 않아도 프로세스가 종료된다.
 
class MyThread5 implements Runnable{
 
    @Override
    public void run() {
        
        for(int i = 1; i <= 20; i++){
            
            System.out.println(i);
            
            try {
                
                Thread.sleep(1000);
                
            } catch (Exception e) {
                // TODO: handle exception
            }
            
        }
                
    }
        
}
 
public class Test5 {
 
    public static void main(String[] args) {
 
        System.out.println("main 시작....");
        
        //일반 스레드
        Thread t1 = new Thread(new MyThread5());
        Thread t2 = new Thread(new MyThread5());
        Thread t3 = new Thread(new MyThread5());
        
        //데몬 스레드 지정    //메인이 진행하는 동안만 진행함    //다른 스레드가 종료 시 데몬스레드는 강제 종료
        t1.setDaemon(true);    //데몬스레드의 기본은 false
        t2.setDaemon(true);
        t3.setDaemon(true);
                
        
        t1.start();
        t2.start();
        t3.start();
        
        try {    //메인절을 1초 쉬어라
            
            Thread.sleep(1000);
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        try {
            //스레드가 종료될때까지 기다렸다가 메인절 종료
            t1.join();//t1이 종료할 때까지 기다려
            t2.join();
            t3.join();
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        System.out.println("main 종료....");
        
    }
 
}
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.day14;
 
//스레드 생명주기(Time to Live:TTL)
 
class MyThread6 extends Thread{
 
    @Override
    public void run() {
        
        try {
            
            System.out.println("스레드 시작");
            
            System.out.println("우선 순위 : " + getPriority());
            System.out.println("스레드 이름 : " + getName());    //내부적 스레드 이름은 0,t1,t2순으로 진행됨
            
            //0.5초 쉼
            sleep(500);
            
            //우선순위 변경
            setPriority(2);
            System.out.println("변경된 우선순위 : " + getPriority());
            
            System.out.println("스레드 종료....");
            
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        
    }
    
}
 
public class Test6 {
 
    public static void main(String[] args) {
        
        Thread t1 = Thread.currentThread();    //currentThread : main스레드
        Thread t2 = new MyThread6();    //upcast
        
        System.out.println("main스레드 우선순위 : " + t1.getPriority());
        
        System.out.println("main스레드 이름 : " + t1.getName());
        
        System.out.println("start()메소드 호출 전의 isAlive : " + t2.isAlive());//false(시작전이기 때문에) //생존여부 확인
        
        t2.start();
 
        //t2의 우선순위
        System.out.println("t2의 우선순위 : " + t2.getPriority());
        
        //t2의 우선순위 변경
        t2.setPriority(1);
        
        try {
            
            //0.1초 쉼
            Thread.sleep(100);
            
            //t2종료 확인
            System.out.println("t2 살아있냐? : " + t2.isAlive());
            
            //1초 쉼
            Thread.sleep(1000);
            
            //t2종료 확인
            System.out.println("1초 후 t2 살아있냐? : " + t2.isAlive());
            
            t2.join();//main 기다려줘
            
            System.out.println("t2 그래도 살아있냐? : " + t2.isAlive());
            
        } catch (Exception e) {
            // TODO: handle exception
        }    
        
    }
 
}
 
cs

==Console==

<인터럽트>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.day14;
 
//인터럽트
//우선순위가 높은 프로그램을 먼저 실행시키고, 다시 돌아온다
//세수 -> 전화 -> 택배 -> 전화 -> 세수 -> 밥 -> 교육원    //진행 하다 우선순위를 실행 후 역순으로 재진행 
 
class MyThread7 extends Thread{
    
    private Thread next;
    
    public void setNext(Thread next){
        
        this.next = next;
        
    }
 
    @Override
    public void run() {
        
        for(int i = 1; i<=20; i++){
            
            try {
                
                sleep(2000);
                
            } catch (Exception e) {
                // TODO: handle exception
            }
            
            System.out.println(getName() + " : " + i);
        
            if(next.isAlive())//아래의 setNext가로 안의 값이 살아 있는지 확인
                
                next.interrupt();    //Thread가 살아있으면 중지시키고 다음 스레드를 진행해라.
            
        }
            
    }
    
}
 
public class Test7 {
 
    public static void main(String[] args) {
        
        MyThread7 t1 = new MyThread7();
        MyThread7 t2 = new MyThread7();
        MyThread7 t3 = new MyThread7();
        
        t1.setNext(t2);    //꼬리물기 실행
        t2.setNext(t3);
        t3.setNext(t1);
        
        t1.start();
        t2.start();
        
        t1.interrupt();
        
    }
 
}
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.day14;
 
class MyThread8 implements Runnable{
    
    private int bank = 10000;
    
    private int getBank(){
        
        return bank;
        
    }
    
    private int drawMoney(int m){
        
        bank -= m; //bank = bank - m;
        return m;
        
    }
 
    @Override
    public void run() {
        
        int money_need = 6000;//인출금액
        
        int money;
        
        String msg = "";
        
        try {
            
            synchronized (this) {//동기화(보호) 블럭
            
                if(getBank()>=money_need){
                    
                    Thread.yield();//yield : 첫번째 스레드가 두번째 스레드에게 양보
                    money = drawMoney(money_need);
                    
                }else{
                    money = 0;
                    msg = "인출실패!!";
                    
                }
            }
            
            System.out.println(Thread.currentThread().getName() + msg + ", 인출금액 : " + money + ", 잔고 : " + getBank());
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        
    }
        
}
 
public class Test8 {
 
    public static void main(String[] args) {
        
        MyThread8 ob = new MyThread8();    
        
        Thread t1 = new Thread(ob);    //interface 사용 시 new MyTread8 대신 ob 사용
        Thread t2 = new Thread(ob);    //Thread는 서로 run을 점유하려고 하기 때문에 겹칠 수 있음.
        
        t1.start();
        t2.start();
        
    }
 
}
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.day14;
 
class MyThread9 implements Runnable{
    
    private int bank = 10000;
    
    private int getBank(){
        
        return bank;
            
    }
    
    private int drawMoney(int m){
        
        if(getBank()>0){
            
            bank -= m;
            
            System.out.println(Thread.currentThread().getName() + ", 인출 : " + m + ", 잔액 : " + bank);
            
        }else{
            
            m = 0;
            System.out.println(Thread.currentThread().getName() + "잔액부족!!");
            
        }
        
        return m;
        
    }
    
    @Override
    public void run() {
    
        synchronized (this) {
            
            for(int i = 1; i<=10;i++){
                
                if(getBank()<=0){
                    
                    this.notifyAll(); //대기상태의 스레드를 시작
                    break;
                    
                }
                
                drawMoney(1000);
                
                if(getBank()==2000||getBank()==4000||getBank()==6000||getBank()==8000){
                    
                    try {
                        
                        wait();    //동기화 안에서 진행중인 스레드를 일시정지 시키고 다른 스레드를 움직이게 해줌
                        //하나의 스레드가 사용중이면 다른 스레드는 동기화 블럭에 들어올 수 없지만 wait()가 있으면 가능하다.
                        //stop의 의미
                        
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    
                }else{
                    
                    notify();    //resume의 의미
                    
                }
                
            }
            
        }
    
    }
    
}
 
public class Test9 {
 
    public static void main(String[] args) {
        
        MyThread9 ob = new MyThread9();
        
        Thread t1 = new Thread(ob);
        Thread t2 = new Thread(ob);
        
        t1.start();
 
    }
 
}
 
cs

===Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.day14;
 
 
//정해진 시간마다 특정 작업을 하고 싶을 때
 
public class Test10 extends Thread {
 
    private int num = 10;
    
    public Test10(){
        
        TimerTask task = new TimerTask() {
                            //무명의 클래스
            @Override
            public void run() {
                //반복 실행할 작업
                num = 0;
                
            }
        };
        
        Timer t = new Timer();    //stopwatch의 개념
        Calendar d = Calendar.getInstance();
        
        /*
         내일 0시 0분 0초부터 하루에 한번씩 반복
         
         d.add(Calender.Date,1);
         d.set(Calender.MINUTE,0); //분 
         d.set(Calender.SECOND,0); //초 
         d.set(Calender.MILLISECOND,0);    //밀리세컨
         t.schedule(task,d.getTime(),1000*60*60*24);    //밀리세컨*초*분*시
         
         */
        
        t.schedule(task, d.getTime(), 5000);
                                    //인터벌(간격) -> 5초마다 진행
        
    }
    
    @Override
    public void run() {
    
        while(true){
            
            System.out.println(num++);
 
            try {
                sleep(500);
            } catch (Exception e) {
                // TODO: handle exception
            }
            
        }
        
    }
    
    public static void main(String[] args) {
        
        //Test10 ob = new Test10();
        //ob.start();
        
        new Test10().start();        
        //객체 생성 없이(메모리 낭비 없이) 최초 1번만 시작버튼을 눌러줌
    }
 
}
 
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.day14;
 
//스레드 그룹
//스레드를 여러개 만들어서 사용할 때 그룹지어 사용
 
public class Test11 {
 
    public static void main(String[] args){
        
        System.out.println("메인 스레드 그룹 : " + Thread.currentThread().getThreadGroup());
        
        System.out.println("메인 : " + Thread.currentThread());
        // [main,5,main] : [name,우선순위,그룹name]
        
        Thread t1 = new Thread();    //main threadgroup에 포함 : main, t1
        
        System.out.println("t1 스레드 그룹 : " + Thread.currentThread().getThreadGroup());
 
        System.out.println("t1 : " + t1); //t1 = Thread.currentThread() 동일함
        //[Thread-0,5,main] : [name,우선순위,그룹name]
        
        System.out.println("--------------------------");
        
        ThreadGroup tg = new ThreadGroup("sg"); //그룹의 이름
        
        Thread t2 = new Thread(tg,"t2");
        Thread t3 = new Thread(tg,"t3");
        
        System.out.println("t2 : " + t2);
        System.out.println("t3 : " + t3);
        
    }
    
}
 
cs

==Console==

 

<ArrayList>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.day13;
 
 
public class Test1 {
 
    public static void main(String[] args) {
 
        ArrayList<String> lists = new ArrayList<String>();
        
        lists.add("서울");
        lists.add("부산");
        lists.add("대구");
        
        Iterator<String> it = lists.iterator();
        
        while(it.hasNext()){
            
            String str = it.next();
            System.out.print(str + " "); //가로로 찍는 방법
            
        }
        
        System.out.println();
        System.out.println("----------------------");
        
        ListIterator<String> it2 = lists.listIterator();
        
        while(it2.hasNext()){
            
            System.out.print(it2.next() + " ");
            
        }
        
        System.out.println();
                        
        //출력 후 데이트는 null
        while(it2.hasNext()){
            
            System.out.print(it2.next() + " ");
            
        }
 
        System.out.println("----------------------");
        
        //역순으로 출력
        //ListIterator<String> it3 = lists.listIterator();
        while(it2.hasPrevious()){
            
            System.out.println(it2.previous());
            
        }
        
        System.out.println("----------------------");
        
        List<String> lists1 = new ArrayList<String>();
        lists1.addAll(lists);
        lists1.add("인천");
        
        int n = lists1.indexOf("부산");//1
        lists1.add(n+1"광주");
        
        for(String c : lists1){
            
            System.out.print(c + " ");
            
        }
        
        System.out.println();
        //------------------------------------------------
        System.out.println("-----------------------");
        
        List<String> lists2 = new ArrayList<String>();
        
        lists2.add("자바프로그래머");
        lists2.add("프레임워크");
        lists2.add("스트럿츠");
        lists2.add("서블릿");
        lists2.add("스프링");
        
        String str;
        Iterator<String> it4 = lists2.iterator();
        while(it4.hasNext()){
            
            str = it4.next();
            if(str.startsWith("서"))
                System.out.println(str);
            
        }
        
    }
 
}
cs

==Console==

<Map>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.day13;
 
 
//Map<키,값> 인터페이스
//Hashtable : vector와 동일(동기화를 지원)
//HashMap : ArrayList와 동일
//키는 중복값을 가질 수 없다.(키는 set이다.)
//키가 중복값을 가지면 마지막 값이 저장(수정)
//Map은 Iterator가 없다.(set의 Iterator를 빌려쓴다.)
//put(입력)
//get(출력)
 
//key라는 고유값을 가지고서 대상을 찾기 때문에 빠름
//반드시 key와 value값을 같이 줘야 함
 
public class Test2 {
 
    public static final String tel[] = {"111-111","222-222","333-333","111-111","444-444"};//key
    
    public static final String name[] = {"이효리","박신혜","한지민","배수지","천송이"};    //value
    
    public static void main(String[] args) {
        
        Hashtable<StringString> h = new Hashtable<StringString>();    //객체 생성
        //map으로 변경 가능
        
        for(int i=0;i<tel.length;i++){
            h.put(tel[i], name[i]);
        }
        
        System.out.println(h);
        //map의 출력 순서는 map만의 정리 방법으로 나옴(들어가는 순서가 아님)
        
        //-----------------------------------
        
        String str;
        str = h.get("111-111"); //키를 주면 value를 반환
        
        System.out.println(str);
        
        //키가 존재하는지 검사
        if(h.containsKey("222-222"))
            System.out.println("222-222가 존재...");
        else
            System.out.println("222-222가 안존재...");
        
        //value가 존재하는지 검사
        if(h.containsValue("배수지"))//띄어쓰기나, 숫자, 글자가 다르면 못찾음
            System.out.println("수지 여기 있어요!");
        else
            System.out.println("수지 없다!");
        
        //데이터 삭제
        h.remove("222-222");
        
        if(h.contains("222-222"))
            System.out.println("222-222가 존재...");
        else
            System.out.println("222-222가 안존재...");
        
        //키는 Set이며, Set은 중복을 허용하지 않는 자료구조이다.
        //Set은 Iterator가 존재하므로 Hashtable 또는 HashMap의
        //keySet()메소드로 Iterator를 사용한다.
        
        Iterator<String> it = h.keySet().iterator();
        //Iterator<key의 자료형> 변수
        
        while(it.hasNext()){
            
            String key = it.next();
            String value = h.get(key);    //value값을 출력하는 방법
            
            System.out.println(key + " : " + value);
            
        }
        
    }
 
}
cs

==Console==

<Set>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package com.day13;
 
 
public class Test3 {
 
    public static void main(String[] args) {
        
        //Set : 중복을 허용하지 않는다
        
        Set<String> s = new HashSet<String>();
        
        s.add("서울");
        s.add("부산");
        s.add("대구");
        
        System.out.println(s);
        
        Iterator<String> it = s.iterator();
        while(it.hasNext()){
            
            String str = it.next();
            System.out.print(str + " ");
            
        }
        
        System.out.println();
 
        
        //중복허용안함
        s.add("서울");
        System.out.println(s);
        
        //Stack
        Stack<String> st = new Stack<String>();
        
        st.push("서울");
        st.add("부산");
        st.push("대구");
        st.push("광주");
        
        //출력한 데이터는 삭제됨
        while(!st.empty()){                //stack이 비어있지 않을 때까지 반복
            
            System.out.print(st.pop() + " ");    //pop : 마지막에 들어간 순서대로 출력
            
        }
        
        System.out.println("\n------------------");
    
        //Queue
        
        Queue<String> q = new LinkedList<String>();    //linkedlist : interface 구현
        //interface의 일종
        
        q.add("서울");
        q.offer("부산");
        q.offer("대구");
        q.offer("광주");
        
        while(q.peek()!=null){    //peek : 들어가있는 데이터가 null이 아닐때까지 꺼낼 것
            
            System.out.print(q.poll() + " "); //poll : 데이터를 꺼내라 
            
        }
        
        System.out.println("\n-------------------");
        
        List<String> lists1 = new LinkedList<String>(); //interface는 다중 구현 가능
        
        lists1.add("A");
        lists1.add("B");
        lists1.add("C");
        lists1.add("D");
        lists1.add("E");
        lists1.add("F");
        lists1.add("G");
        lists1.add("H");
        
        List<String> lists2 = new LinkedList<String>();
        
        lists2.add("서울");
        lists2.add("부산");
        lists2.add("대구");
        
        lists2.addAll(lists1);    //list2 나오고 뒤로 list1을 붙여줌
        for(String ss : lists1){
            System.out.print(ss + " ");
        }
        System.out.println();
        
        for(String ss : lists2){
            System.out.print(ss + " ");
        }
        System.out.println();
        
        System.out.println("-------------------");
        
        //범위삭제
        lists2.subList(25).clear();    //index 2에서 (5-1)까지의 범위를 삭제하고 빈공간은 다시 위치 조정
        for(String ss : lists2){
            System.out.print(ss + " ");
        }
        System.out.println();
        
        //-----------------------------------------------
        
        String[] str = {"다","바","나","가","마","라"};
        
        for(String ss : str)
            System.out.print(ss + " ");
        
        System.out.println();
        
        //배열 정렬
        Arrays.sort(str);    //array에 s 꼭 붙여줘야 함
        
        for(String ss : str)
            System.out.print(ss + " ");
        
        System.out.println();
        
    }
 
}
 
/*
  
 [List]
 List<저장할 자료형> list = new ArrayList<저장할 자료형>();    //사용방법 기억
 List<저장할 자료형> list = new Vector<저장할 자료형>();
 
 ArrayList<저장할 자료형> list = new ArrayList<저장할 자료형>();
 Vector<저장할 자료형> list = new Vector<저장할 자료형>();
 
 add : 추가
 size : 요소객수(데이터 갯수)
 remove(index) : 삭제
 clear : 전체 데이터 삭제
 trimtoSize : 빈공간 삭제
  
 Iterator<저장된자료형> it = list.Iterator();
 while(it.hasNext){
 저장된 자료형 value = it.next();
 }
 
 ---------------------------------------------------------------------
 
 [Map]
 Map<키자료형, 저장할자료형> map = new HashMap<키자료형, 저장할자료형>();    //사용방법 기억(주로 hashmap 사용)
 Map<키자료형, 저장할자료형> map = new Hashtable<키자료형, 저장할자료형>();
 
 HashMap<키자료형, 저장할자료형> map = new HashMap<키자료형, 저장할자료형>();
 Hashtable<키자료형, 저장할자료형> map = new Hashtable<키자료형, 저장할자료형>();
 
 put(key, value) : 추가
 remove(key) : 삭제
 clear() : 전체삭제
 
 Iterator<키자료형> it = map.keyset().Iterator();
 while(it.hasNext){
 키자료형 key = it.next();
 저장된자료형 value = map.get(key);
 }
  
 */
 
 
cs

==Console==

 

 

<Generic>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.day13;
 
//Generic
class Box<T>{
 
    private T t;    //정해지지 않은 자료형
    
    public void set(T t){    //자료형에 set를 활용하여 데이터타입을 적용해줌
        
        this.t = t;
        
    }
    
    public T get(){
        
        return t;
        
    }
    
}
 
// Generic의 단점 : 느리다
public class Test4 {
 
    public static void main(String[] args) {
        
        Box<Integer> b1 = new Box<Integer>();
        
        b1.set(new Integer(10)); //랩퍼클래스의 객체 생성
        Integer i = b1.get();
        System.out.println(i);
        
        //------------------------------------------------
        
        Box<String> b2 = new Box<String>();
        
        b2.set("서울");
        String s = b2.get();
        System.out.println(s);
        
        //-----------------------------------------------
        
        Box b3 = new Box();    //box 안의 데이터 타입은 object
        
        b3.set(30);//upcast
        
        Integer ii = (Integer)b3.get();//downcast
        System.out.println(ii);
        
    }
 
}
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.day13;
 
class Box2<T>{
    
    private T t;
    
    public void set(T t){
        this.t = t;
    }
    
    public T get(){
        return t;
    }
    
    public <U> void print(U u){
        System.out.println(t);
        System.out.println(u);
        System.out.println("t 클래스 : " + t.getClass().getName());
        System.out.println("u 메소드 : " + u.getClass().getName());
    }
    
}
 
public class Test5 {
 
    public static void main(String[] args) {
        
        Box2<Integer> b = new Box2<Integer>();    //box의 T 는 Integer가 됨
        //앞의 Integer 반드시 작성    //뒤의 Integer 생략가능
        
        b.set(new Integer(30));    //t클래스는 Integer가 됨    //T를 초기화
        
        b.print("test");    //u클래스는 String이 됨            //메소드 초기화
        
        b.print(50);        //u클래스는 Integer가 됨        
 
    }
 
}
cs

==Console==

<예외처리>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.day13;
 
import java.util.Scanner;
 
//Exception 클래스(예외처리)
 
//runtime오류 : 코딩상에는 문제 없으나, 예상못한 값을 입력했을 시 발생
public class Test6 {
 
    public static void main(String[] args) {
        
        int a,b,result;
        String oper;
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        try {    //ms에서 만들어진 방법
        
        //try부분에서 에러가 발생 시 catch에서 잡아내서 exception이 처리해서 e에 결과 출력
            
            System.out.print("첫번째수? ");
            a = Integer.parseInt(br.readLine());
            
            System.out.print("두번째수? ");
            b = Integer.parseInt(br.readLine());
            
            System.out.print("연산자? ");
            oper = br.readLine();
            
            result = 0;
            
            if(oper.equals("+")){
                result = a + b;
            }else if(oper.equals("-")){
                result = a - b;
            }else if(oper.equals("*")){
                result = a * b;
            }else if(oper.equals("/")){
                result = a / b;
            }
            
            System.out.printf("%d %s %d = %d\n",a,oper,b,result);
            
        // 예외를 나눠서 구분 가능
        } catch(NumberFormatException e){
            System.out.println("정수를 입력해라!!");
        } catch(ArithmeticException e){
            System.out.println("0으로 나누면 안돼!!");
        } catch (IOException e) {
            System.out.println("넌 그게 숫자로 보이냐?");
            //System.out.println(e.toString());
            e.printStackTrace();    //에러메세지 출력
        } finally{//항상 해줘야 하는 작업(코딩)을 사용
            System.out.println("난 항상 보인다!!");
        }
        
        System.out.println("여기는 try 밖...");
        
        
        
        
        
        
 
    }
 
}
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.day13;
 
 
public class Test7 {
 
    public static String getOper() throws Exception{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String oper = null;
        
        try{
            
            System.out.print("연산자? ");
            oper = br.readLine();
            
            if(!oper.equals("+")&&!oper.equals("-")&&!oper.equals("*")&&!oper.equals("/")){
                
                //throw로 예외를 의도적으로 발생 시킴
                //throw를 사용하려면 반드시 throws Exception을 기술한다.
                //try.catch문으로 감싸준다.
                throw new Exception("연산자 입력 오류!!");
                
            }
            
        }catch(Exception e){
            
        }
        return oper;
        
    }
    
    public static void main(String[] args) {
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int a,b,result;
        String oper;
        
        try {
            System.out.print("첫번째수? ");
            a = Integer.parseInt(br.readLine());
            
            System.out.print("두번째수? ");
            b = Integer.parseInt(br.readLine());
            
            oper = Test7.getOper();
            
            result = 0;
            
            if(oper.equals("+")){
                result = a + b;
            }else if(oper.equals("-")){
                result = a - b;
            }else if(oper.equals("*")){
                result = a * b;
            }else if(oper.equals("/")){
                result = a / b;
            }
            
            System.out.printf("%d %s %d = %d\n",a,oper,b,result);
            
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
    }
 
}
 
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.day12;
 
//내부클래스(inner)    : 클래스를 내가 만들고 싶은 곳에 만들 수 있음(ex.클래스 안, 메소드 안...)
//1.클래스 안에 클래스를 생성 가능
//단, 중괄호가 겹치면 안됨
 
class Outer1{//Outer1.class
    
    static int a= 10;
    int b= 20;
    
    //Inner를 사용하려면 Outer의 객체를 생성
    //Outer의 객체가 생성됐다고 Inner가 생성된건 아니다
    public class Inner1{//Outer1$Inner1.class
        
        int c = 30;
        
        public void write(){
            
            System.out.println(a);
            System.out.println(b);
            System.out.println(c);
            
        }
                
    }
        
    public void print(){
        
        Inner1 ob = new Inner1();
        ob.write();
        
    }
    
}
 
public class Test1 {
    
 
    public static void main(String[] args) {
 
        Outer1 out = new Outer1();        
        out.print();//1번째 방법     //Outer의 메소드를 이용하여 Inner의 메소드를 사용
        
        System.out.println("----");
        
        Outer1.Inner1 inner = out.new Inner1();//2번째 방법
        inner.write();
        
    }
 
}
cs

==Console==

<InnerClass>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.day12;
 
//내부클래스(inner)    : 클래스를 내가 만들고 싶은 곳에 만들 수 있음(ex.클래스 안, 메소드 안...)
//2.메소드 안에 클래스를 생성 가능
//단, 중괄호가 겹치면 안됨
 
class Outer2{
    
    static int a = 10;    //전역변수
    int b = 20;
    
    public void write(){
        
        int c = 30;    //지역변수
        final int d = 40;    
        
        class Local{//메소드 안에 클래스 생성 시 객체 생성은 무조건 메소드 안에서 생성 필요
            
            public void print(){
                
                System.out.println(a);
                System.out.println(b);
                System.out.println(c);
                System.out.println(d);                
                
            }            
            
        }
        
        //메소드 안에서만 객체 생성 가능
        Local ob = new Local();
        ob.print();
        
    }
        
}
 
public class Test2 {
 
    public static void main(String[] args) {
        
        Outer2 out = new Outer2();
        out.write();
 
    }
 
}
 
cs

==Console==

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.day12;
 
//내부클래스(중첩)    : 클래스를 내가 만들고 싶은 곳에 만들 수 있음(ex.클래스 안, 메소드 안...)
//3. 클래스 안에 static 클래스를 생성 가능
//단, 중괄호가 겹치면 안됨
 
class Outer3{
    
    static int a = 10;
    int b = 20;
    
    public static class Inner3{
        
        int c = 30;
        
        public void write(){
            
            System.out.println(a);
            //System.out.println(b);
            System.out.println(c);
            
            Outer3 out = new Outer3();//1번째 방법 : outer를 inner 내부에서 객체를 생성하여 출력
            System.out.println(out.b);
                
        }
            
    }
    
    public void print(){
        
        Inner3 ob = new Inner3();
        ob.write();
        
    }
    
}
 
public class Test3 {
 
    public static void main(String[] args) {
        
        Outer3 out = new Outer3();//2번째 방법 : inner의 객체를 outer에 생성 후 outer를 메인절에서 객체 생성하여 출력
        out.print();
        
        //클래스 안의 클래스 생성 시 :     Outer3.Inner3 inner = out.new Inner3();
        Outer3.Inner3 inner = new Outer3.Inner3();
        inner.write();
        
    }
 
}
cs

==Console==

<익명의 annonymous,무명의 클래스>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.day12;
 
//내부클래스(inner)    : 클래스를 내가 만들고 싶은 곳에 만들 수 있음(ex.클래스 안, 메소드 안...)
//4.익명의 annonymous,무명의 클래스
//메모리 낭비가 적다(안드로이드 제작할 때 많이 사용) : 사용하고 초기화 하기 위해서 사용
//단, 중괄호가 겹치면 안됨
 
//저장되는 이름 : Test4$1.class
 
public class Test4 {
    
    public Object getTitle(){
        
        //코딩
        
        //return a;
        return new Object(){//객체의 명칭이 없이 한번 쓰고 없어지는 객체
            
            @Override
            public String toString() {
                return "익명의 클래스";
            }
                        
        };
        
    }
    
    public static void main(String[] args) {
 
        Test4 ob = new Test4();
        System.out.println(ob.getTitle());
        
    }
 
}
 
cs

==Console==

 

<Collection Framework>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.day12;
 
 
//ms의 framework : .net은 os를 실행하는데 famework를 완충지대로 os를 컨트롤하고 h/w를 컨트롤 
//웹의 framework : (strat, ibatis, mybatis, spring 등) jsp,servlet 등의 코딩을 쉽게 만들고 보수할 수 있게 하는 방법론 
 
//Collections Framework(방법론) : 데이터를 관리하는 방법론
//데이터 관리의 진화 : 변수 -> 배열 -> 클래스 -> collection framework
 
//Collections Framework의 종류
//List(Vector(동기화 o),ArrayList(동기화 x : 주로 사용)...) - interface의 일종
//Map(HashSet,HashTable,TreeSet...) - interface의 일종
 
//객체 생성 시 공간이 기본 10개가 생성
//공간 늘리기, 줄이기 가능
//중간 삽입 가능(밀어내기)
 
//List(I) - Vector(C)
//inetface는 객체 생성이 안되고 클래스를 생성하여 구현함
public class Test5{
 
    public static void main(String[] args) {
        
        Vector v = new Vector();
 
        v.add("서울");    //upcast
        v.add(30);
        v.add('c');
        //vector의 데이터 타입: objct
        
        String str;
        Integer i;
        Character c;
        
        str = (String) v.get(0);    //downcast
        System.out.println(str);
        
        i = (Integer)v.get(1);
        System.out.println(i);
        
        c = (char)v.get(2);
        System.out.println(c);
        
        Iterator it = v.iterator();
        
        while(it.hasNext()){    //데이터 유무 확인 (맨위 bof에서 대기, 데이터 아래 eof에서 종료)
            
            Object o = it.next();    //데이터의 타입을 알 수 없기 때문에 object로 호출
            
            if(o instanceof String){
                str = (String)o;
                System.out.println(str);
            }else if(o instanceof Integer){
                i = (Integer)o;
                System.out.println(i);
            }else if(o instanceof Character){
                c = (char)o;
                System.out.println(c);
                
            }
            
        }
        
    }
 
}
 
cs

==Console==

<Vector와 Iterator의 등장>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.day12;
 
 
public class Test6 {
 
    private static final String city[] = {"서울","부산","대구","인천","광주","대전","울산"};
        
    public static void main(String[] args) {
 
        Vector<String> v = new Vector<String>();    //제너릭 : vector에 String값만 넣을 수 있게 설정
        
        for(String s : city){
            v.add(s);
        }
        
        //v.add(10);
        
        String str;
        str = v.get(0);    //vecter에 string만 들어가 있기 때문에 upcast가 진행 안되어서 downcast도 진행 안함
        System.out.println(str);        
        
        str = v.firstElement();
        System.out.println(str);
        
        str = v.lastElement();
        System.out.println(str);
        
        str = v.get(1);
        System.out.println(str);
        //---------------------------------------
        for(int i=0;i<v.size();i++){    //vector는 length가 아닌 size 사용
            System.out.print(v.get(i)+" ");
        }
        System.out.println();
        //---------------------------------------
        for(String s : v){
            System.out.print(s + " ");
        }
        System.out.println();
        //---------------------------------------
        
        //vector의 고유 반복문
        //Iterator : 반복자
        
        Iterator<String> it = v.iterator();
        
        while(it.hasNext()){    //hasNext()데이터를 읽는 하이라이트바를 옮겨주는 기능
        
            str = it.next();
            
            System.out.print(str + " ");
            
        }    //Iterator set
        
        while(it.hasNext()){ //move의 개념으로 사용하기 때문에 첫번째 while문에서 it 내용을 사용하고 
                             //더이상 데이터가 없기 때문에 호출 불가(데이터 없음)
            
            str = it.next();
            
            System.out.print(str + " ");
            
        }
        
        
    }
 
}
 
cs

==Console==

 

<Generic>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package com.day12;
 
 
public class Test7 {
    
    private static final String city[] = {"서울","부산","대구","인천","광주","대전","울산"};
 
    public static void main(String[] args) {
 
        //제너릭(generic)
        Vector<String> v = new Vector<String>();
        
        String str;
        
        System.out.println("벡터의 초기 용량 : " + v.capacity());    //vector의 초기 용량은 10개
 
        for(String c : city){
            
            v.add(c);
            
        }
        
        Iterator<String> it = v.iterator();
        
        while(it.hasNext()){
            
            str = it.next();
            System.out.print(str + " ");
            
        }
        
        System.out.println();
        
        //데이터 변경(수정)
        v.set(0"Seoul");
        v.set(1"Busan");
        
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
        
        //----------------------------------------
        
        //삽입(끼워넣기)
        v.insertElementAt("대한민국"0);
        
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
        
        //----------------------------------------
        //검색
        
        int index = v.indexOf("대구");
        if(index != -1){
            System.out.println("검색 성공!" + index);
            System.out.println(v.get(index));
        }else{
            System.out.println("검색 실패!" + index);
        }
        
        //----------------------------------------
        
        //오름차순 정렬(1~10,a~z,ㄱ~ㅎ)
        Collections.sort(v);
        
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
        
        //----------------------------------------
        
        //내림차순 정렬(10~1,z~a,ㅎ~ㄱ)
                                        //정렬 방법
                
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
        
        //----------------------------------------
        
        //삭제
        v.remove("Busan"); //v.remove(7);
        
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
        
        //----------------------------------------
        System.out.println("벡터의 초기 용량 : " + v.capacity());
        //----------------------------------------
        
        //용량 증가
        
        for(int i=1;i<=20;i++){
            
            v.add(Integer.toString(i));
            
        }
        
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
        
        System.out.println("벡터의 용량 : " + v.capacity());
 
        //----------------------------------------
 
        //특정 범위 삭제
        //v.removeRange(5,20) //5~20번째까지 삭제(현재 없어짐(jdk7.0)까지 가능함)
        
        for(int i = 1;i<=10; i++){
            v.remove(5);
        }
        
        for(String s:v){
            System.out.print(s + " ");
        }
        System.out.println();
 
        System.out.println("벡터의 용량 : " + v.capacity());
 
        //----------------------------------------
        
        //빈공간 삭제
        
        v.trimToSize();
        
        System.out.println("벡터의 용량 : " + v.capacity());
        
        //----------------------------------------
        
        //모든 데이터 지우기
        
        v.clear();
        System.out.println("데이터 갯수 : " + v.size());
        System.out.println("벡터의 용량 : " + v.capacity());
        
        v.trimToSize();
        System.out.println("데이터 갯수 : " + v.size());
        System.out.println("벡터의 용량 : " + v.capacity());
        
    }
 
}
cs

==Console==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.day12;
 
 
class Test{
    
    String name;
    int age;    
    
}
 
public class Test8 {
 
    public static void main(String[] args) {
        
        Vector<Test> v = new Vector<Test>();
        
        Test ob;
        
        ob = new Test();
        
        ob.name = "배수지";
        ob.age = 25;
        
        v.add(ob);    //ob의 주소를 복사해서 첫번째 공간에 들어감
        
        //-------------------------------------------------------
        
        ob = new Test();    //기존 ob의 주소를 단절, 새로운 주소와 연결
        
        ob.name = "박신혜";
        ob.age = 27;
        
        v.add(ob);    //ob의 주소를 복사해서 두번째 공간에 들어감
        
        for(Test t : v)
            System.out.println(t.name + " : " + t.age);
 
    }
 
}
 
cs

==Console==

<추상 클래스>

==Console==

==Console==

 

==Console==

<Interface 인터페이스>

==Console==

==Console==

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.day11;
 
//inetface가 interface 상속 예제
 
import java.util.Scanner;
 
interface FruitA{
    
    String Won = "원";    //public static final 생략
    
    public int getPrice();
    public String gerName();
    
}
 
interface ItemFruit extends FruitA{    //interface가 다른 interface를 상속
    
    public String getItems();    
    
}
 
class Orange implements ItemFruit{    //override 3개 적용(FruitA 2개, ItemFruit 1개)
 
    @Override
    public int getPrice() {
        return 1500;
    }
 
    @Override
    public String gerName() {
        return "오렌지";
    }
 
    @Override
    public String getItems() {
        return "과일";
    }
        
}
 
class Apple implements ItemFruit{
 
    @Override
    public int getPrice() {
        return 2000;
    }
 
    @Override
    public String gerName() {
        return "사과";
    }
 
    @Override
    public String getItems() {
        return "과일";
    }
    
}
 
public class Test7 {
    
    public void packing(ItemFruit ob){    //ItemFruit ob 에 클래스를 받을 수 있음(ex.new Orange를 넣어줌)
        System.out.println(ob.getItems());
        System.out.println(ob.gerName());
        System.out.println(ob.getPrice()+FruitA.Won);
    }
 
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        Test7 t = new Test7();
        
        System.out.print("1.오렌지 2.사과 : ");//1  2
        int ch = sc.nextInt();
        
        if(ch==1){
            t.packing(new Orange());    // ItemFruit ob = new Orange();
            
        }else if(ch==2){
            t.packing(new Apple());        // ItemFruit ob = new Apple();
            
        }
        
        
/*        ItemFruit ob;
        
        ob = new Orange();
        
        System.out.println("----------------");
        
        //ItemFruit ob2;
        ob = new Apple();
        
        System.out.println("----------------");
*/
        /*
         int a;
         a = 10;
         System.out.println(a);
         
         a = 20;
         System.out.println(a);
         
         */
        
    }
 
}
 

==Console==

<Calendar을 이용한 만년달력>

==Console==

<String 의 주요 메소드>

==Console==

 

==Console==

<Wrapper Class>

==Console===

==Console==(현재시스템의 시간)

<Singleton>

<final>

==Console==

==Console==

 

==Console==

+ Recent posts