SKILL/JAVA

자바 List, Iterator

Jedy_Kim 2017. 12. 15. 12:40
728x90
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
package com.bit.d1215;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/*
 *  List 주요 메서드
 *  -add    : 데이터 입력
 *  -addAll : 기존 저장된 데이터 집합 객체의 데이터 입력
 *  -get    : 데이터 추출
 *  -size    : 입력된 데이터의 개수
 *  -remove    : 특정 데이터 삭제
 *  -clear     : 모든 데이터 삭제
 *  -contains: 특정 객체의 존재여부 체크
 *  -isEmpty: 비어있는지 여부 체크
 *  
 *  -iterator: 객체 반환 목적 (반복자)
 * 
 */
public class ListMain {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>(); //List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        
        list.add("two"); //데이터 중복 허용!
        
//        for (int i = 0; i<list.size(); i++) {
//            System.out.println(list.get(i));
//        }
//        
//        for(String s : list) {
//            System.out.println(s);
//        }
        
        /*
         *     Iterator 메서드
         *     - hasNext()            : 요소의 존재유무 판단
         *  - next()            : 요소를 추출
         *  - remove()            : 요소를 삭제           
         */
        Iterator<String> ite = list.iterator();
        while(ite.hasNext()) {
            System.out.println(ite.next());
        }
        List<String> sub = new ArrayList<String>();
        sub.add("3");
        sub.add("5");
        sub.add("7");        
        list.addAll(sub);
        ite = list.iterator();
        while(ite.hasNext()){
            System.out.println(ite.next());
        }
        
        String str = "five";
        if(list.contains(str)) {
            System.out.println(str + "데이터 존재");
        } else {
            System.out.println(str + "데이터 미존재");
        }
        
        System.out.println("삭제 전 데이터 개수 : " + list.size());
        String delStr = list.remove(0);
        System.out.println("삭제 된 데이터 : " + delStr);
        boolean bool = list.remove("one");
        System.out.println(bool? "삭제성공" : "삭제실패");
        System.out.println("삭제 후 데이터 개수 : " + list.size());
        
        list.clear();
        System.out.println("모두 삭제 후 데이터 개수 : " + list.size());
        
        if(list.size() == 0) {
//        if(list.isEmpty()) {
            System.out.println("요소가 존재하지 않습니다.");
        } else {
            System.out.println("리스트의 요소가" + list.size() + "만큼 있습니다.");
        }
    }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
//
 
cs


반응형

'SKILL > JAVA' 카테고리의 다른 글

자바 제네릭클리스 기본  (0) 2017.12.15
자바 Set컬렉션  (0) 2017.12.15
자바 사용자 예외처리  (0) 2017.12.15
자바 예외처리 예제 try~ catch~ final~  (0) 2017.12.15
자바 추상클래스  (0) 2017.12.15