일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 싱글톤 패턴
- tomat
- Spring 구조
- New Dialog
- spring 페이징
- java
- JDK 설치
- Unbox
- 오버로딩
- singleton
- 오라클 데이터베이스
- 접근제한수식어
- SPRING 특징
- Runnable
- File
- DB 설정
- Overloading
- OuterClass
- 톰켓
- 자바 개발환경준비
- Statement
- New Frame
- append()
- Spring 개념
- pox.xml 오류
- innerclass
- protected
- inheritance
- Visuall code
- 드림코딩
- Today
- Total
~홍~
Java _ Collection 12 본문
Collection 01
public class ListMain01 {
public static void main(String[] args) {
int[] list1 = new int[3];
list1[0] = 1;
System.out.println(list1.length);
// 배열의 길이는 데이터가 저장된 개수와 상관없이 고정
// 배열에 저장된 데이터의 개수를 확인하기 어려움
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("리스트 크기 : " + list.size());
// ArrayList에 원소(element) 추가 : add() 메소드 사용
list.add(100); // index = 0
list.add(200); // index = 1
list.add(300); // index = 2
list.add(400); // index = 3
System.out.println("리스트 크기 : " + list.size());
// ArrayList에 있는 원소 참조(읽기) : get(index) 메소드 사용
System.out.println(list.get(0));
System.out.println(list.get(2));
System.out.println();
// for-each()
// for (원소타입 변수이름 : 배열 또는 리스트이름) {...}
for (Integer n : list) {
System.out.println(n);
}
System.out.println();
// ArrayList에서 특정 인덱스의 원소를 변경 : set(index, value)
list.set(0, 1);
list.set(2, 123456);
for(Integer n : list) {
System.out.println(n);
}
System.out.println();
// ArrayList에서 특정 인덱스의 원소를 삭제 : remove(index)
list.remove(2);
System.out.println("리스트 크기 : " + list.size());
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} // end main()
} // end ListMain01
출력
3
리스트 크기 : 0
리스트 크기 : 4
100
300
100
200
300
400
1
200
123456
400
리스트 크기 : 3
1
200
400
Collection 02
Student
class Student {
// 멤버 변수
private int stuNo;
private String name;
public Student(int stuNo, String name) {
this.stuNo = stuNo;
this.name = name;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
String str = "번호 : " + stuNo + "\n"
+ "이름 : " + name;
return str;
}
}
Main
public class ListMain02 {
public static void main(String[] args) {
Student[] list1 = new Student[3];
// Student 타입을 저장할 수 있는 ArrayList 인스턴스 생성
ArrayList<Student> list = new ArrayList<Student>();
// index : 리스트 내부의 접근 번호
// element : 리스트의 타입에 맞는 객체를 저장
// list에 stuNo = 1, name = "kim"인 학생의 데이터를 등록하시오
Student stu1 = new Student(1, "kim");
list.add(stu1);
list.add(new Student(2, "park"));
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("==========");
list.set(0, new Student(3, "choi"));
for(Student s : list) {
System.out.println(s);
}
System.out.println("==========");
list.remove(0);
for (Student s : list) {
System.out.println(s);
}
} // end main()
} // end ListMain02
출력
번호 : 1
이름 : kim
번호 : 2
이름 : park
==========
번호 : 3
이름 : choi
번호 : 2
이름 : park
==========
번호 : 2
이름 : park
Collection 03
// Collection<E> : 자료(데이터)를 저장하기 위한 generic 클래스
// |_ List<E>, Set<E>
// List<E> :
// 1. 자료들이 저장되는 순서가 중요 -> 인덱스 사용
// 2. 중복된 값들의 저장을 허용
//
// List<E>
// |_ ArrayList<E>, LinkedList<E>
// ArrayList<E>
// 1. 내부적으로 배열 자료 구조를 사용
// 2. 저장 용량을 늘리는데 많은 시간이 소요됨 - 단점
// 3. 저장된 데이터를 삭제하는데 많은 시간이 소요됨 - 단점
// 4. 데이터를 참조(검색)할 때 매우 빠름 - 장점
// LinkedList<E>
// 1. 내부적으로 Linked List 자료구조를 사용
// 2. 저장 용량을 늘리는 과정이 매우 간단 - 장점
// 3. 저장된 데이터를 삭제하는 과정도 매우 간단 - 장점
// 4. 데이터를 참조(검색)하는 시간이 매우 느림 - 단점
// ArrayList<E>, LinkedList<E> 에서 사용되는 메소드들 :
// add(element), get(index), set(index, element), remove(index)
public class CollectionMain03 {
public static void main(String[] args) {
// String을 저장할 수 있는 LinkedList 객체 생성
List<String> list = new LinkedList<String>(); // 다형성
list.add("목요일");
list.add("입니다.");
list.add("내일은");
list.add("금요일입니다.");
for(String x : list) {
System.out.println(x);
}
list.set(3, "행복한 금요일");
for(String x : list) {
System.out.println(x);
}
list.remove(3);
for(String x : list) {
System.out.println(x);
}
} // end main()
} // end CollectionMain03
출력
목요일
입니다.
내일은
금요일입니다.
목요일
입니다.
내일은
행복한 금요일
목요일
입니다.
내일은
Collection 04
Student
public class Student {
// 멤버 변수
private String name;
private Score score;
// 기본, 매개변수 생성자 작성
public Student() {}
public Student(String name, Score score) {
this.name = name;
this.score = score;
}
// getter/setter 작성
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
}
Score
public class Score {
// 멤버 변수
private int math;
private int eng;
// 기본, 매개변수 생성자 작성
public Score() {}
public Score(int math, int eng) {
super();
this.math = math;
this.eng = eng;
}
// getter/setter 작성
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
}
Main
public class CollectionMain04 {
public static void main(String[] args) {
// 수학/영어 점수 입력받아서 Score 객체 생성
// 이름을 입력받고, 이름과 Score객체를 이용하여 Student 객체 생성
// LinkedList를 생성하여 Student 객체를 저장
// 위를 3번 반복해서 LinkedList에 총 3개의 객체가 들어가도록 코드 작성
Scanner sc = new Scanner(System.in);
List<Student> list = new LinkedList<Student>();
for(int i = 0; i < 3; i++) {
System.out.println("수학 점수 입력>");
int math = sc.nextInt();
System.out.println("영어 점수 입력>");
int eng = sc.nextInt();
sc.nextLine();
Score score = new Score(math, eng);
System.out.println("이름 입력");
String name = sc.nextLine();
Student student = new Student(name, score);
list.add(student);
}
// 전체 데이터 검색(출력)
for(int i = 0; i < list.size(); i++) {
System.out.println("--- 학생[" + i + "] 정보 ---");
Student s = list.get(i);
System.out.println("이름 : " + s.getName());
System.out.println("수학 : " + s.getScore().getMath());
System.out.println("영어 : " + s.getScore().getEng());
}
// 출력 예시)
// --- 학생[0] 정보 ---
// 이름 : kim
// 수학 : 100
// 영어 : 100
// --- 학생[1] 정보 ---
// ...
// 수정 : 1번 인덱스 학생의 정보 변경
Score score = new Score(100, 50);
Student stu = new Student("둘리", score);
list.set(1, stu);
// 0번 인덱스 학생의 영어점수만 변경
list.get(0).getScore().setEng(80); // 영어 점수 변경
list.get(0).getScore().setMath(100); // 수학 점수 변경
System.out.println("--- 변경 후 ---");
for(int i = 0; i < list.size(); i++) {
System.out.println("--- 학생[" + i + "] 정보 ---");
Student s = list.get(i);
System.out.println("이름 : " + s.getName());
System.out.println("수학 : " + s.getScore().getMath());
System.out.println("영어 : " + s.getScore().getEng());
}
// 삭제 : 1번 인덱스 학생의 정보 삭제
list.remove(1);
System.out.println("--- 삭제 후 ---");
for(int i = 0; i < list.size(); i++) {
System.out.println("--- 학생[" + i + "] 정보 ---");
Student s = list.get(i);
System.out.println("이름 : " + s.getName());
System.out.println("수학 : " + s.getScore().getMath());
System.out.println("영어 : " + s.getScore().getEng());
}
} // end main()
} // end CollectionMain04
Collection 05
// Collection<E>
// |_ Set<E>
// |_ HashSet<E>, TreeSet<E>
// Set<E> :
// 1. 데이터의 저장 순서가 중요하지 않음 -> 인덱스가 없음
// 2. 중복된 데이터의 저장을 허용하지 않음
// 예) {1, 2, 2, 3, 3, 3} = {1, 2, 3}
// HashSet<E> : 검색을 빠르게 하기 위한 Hash 알고리즘이 적용된 Set
// TreeSet<E> : 정렬을 빠르게 하기 위한 Tree 알고리즘이 적용된 Set
public class CollectionMain05 {
public static void main(String[] args) {
// HashSet<Integer> 객체 생성
Set<Integer> set = new HashSet<Integer>(); // 다형성
// Set에 데이터 저장 : add(element)
set.add(300);
set.add(100);
set.add(200);
set.add(100);
System.out.println("Set size : " + set.size());
// Set<E>은 인덱스로 데이터를 읽어올 수 있는 get() 메소드를 제공하지 않음
for (Integer x : set) {
System.out.println(x);
}
System.out.println();
// Iterator(반복자)를 사용한 데이터 검색
// - Iterator 메소드
// iterator() : Iterator 객체를 리턴
// hasNext() : Iterator 객체가 가리키는 위치에
// 원소가 있는지(true), 없는지(false)를 리턴하는 메소드
// next() : Iterator 객체가 가리키는 위치를 다음 위치로 이동하고,
// 원래 가리키고 있던 값을 리턴하는 메소드
Iterator<Integer> itr = set.iterator();
while(itr.hasNext()) {
System.out.println("원소 존재? " + itr.hasNext() + " 데이터 : " + itr.next());
}
// Iterator 인터페이스 : 컬렉션 프레임워크의 표준 인터페이스
List<Integer> list = new ArrayList<Integer>();
list.iterator();
System.out.println();
// Set<E>의 원소를 삭제 : remove(element)
// 인덱스가 아니라 값으로 삭제
set.remove(300);
System.out.println("--- 삭제 후 ---");
for (Integer x : set) {
System.out.println(x);
}
// Set<E>은 인덱스가 없기 때문에,
// 데이터 변경을 위한 set(index, element) 메소드를 제공하지 않음
// 데이터 변경 => 데이터 삭제(remove) + 데이터 추가(add)
set.remove(200);
set.add(500);
System.out.println("--- 변경 후 ---");
for (Integer x : set) {
System.out.println(x);
}
} // end main()
} // end CollectionMain05
출력
Set size : 3
100
200
300
원소 존재? true 데이터 : 100
원소 존재? true 데이터 : 200
원소 존재? true 데이터 : 300
--- 삭제 후 ---
100
200
--- 변경 후 ---
100
500
Collection 06
public class CollectionMain06 {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<String>();
// 데이터 저장 : add(element)
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
// TreeSet<E>인 경우
// iterator() : 오름차순 Iterator 객체 생성
// descendingIterator() : 내림차순 Iterator 객체 생성
// -> HashSet<E>은 내림차순 Iterator가 없음
// lexicographical order : 사전식 정렬
Iterator<String> itr = set.descendingIterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
} // end main()
} // end CollectionMain06
출력
Two
Three
One
Four
Five
Collection 07
// List<E>, Set<E> : 한 가지 타입의 데이터를 저장할 수 있는 Collection
// Map<K, V> : Key-Value 쌍으로 데이터를 저장하는 구조
// 1. Key는 중복되지 않는 값만 저장 가능
// 2. Value는 중복된 값도 저장 가능
// 3. 검색, 수정, 삭제할 때 Key값을 사용함
// HashMap<K, V> : 검색을 빠르게 하기 위한 Hash 알고리즘이 적용된 Map
// TreeMap<K, V> : 정렬을 빠르게 하기 위한 Tree 알고리즘이 적용된 Map
public class CollectionMain07 {
public static void main(String[] args) {
// TreeMap<Integer, String> 객체 생성
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
// Map<K, V>에 데이터 저장 : put(key, value)
map.put(10, "이승우");
map.put(16, "손흥민");
map.put(22, "이강우");
System.out.println(map);
System.out.println();
// Map<K, V>의 데이터 하나 검색 : get(key)
// - 해당 key 값의 value를 리턴
System.out.println(map.get(10));
System.out.println(map.get(22));
System.out.println(map.get(100));
System.out.println();
// Map<K, V>에서 데이터를 수정 : put(key, value)
map.put(10, "김병지");
System.out.println(map.get(10));
System.out.println(map);
System.out.println();
// Map<K, V>에서 데이터를 삭제 : remove(key)
map.remove(10);
System.out.println(map);
System.out.println();
// Map<K, V>에서 key들로만 이루어진 Set을 생성 : KeySet()
Set<Integer> keySet = map.keySet(); // 오름차순 키 set
// map.descendingKeySet(); // 내림차순 키 set
System.out.println(keySet);
for (Integer key : keySet) {
System.out.println(key + "번 " + map.get(key));
}
} // end main()
} // end CollectionMain07
출력
{10=이승우, 16=손흥민, 22=이강우}
이승우
이강우
null
김병지
{10=김병지, 16=손흥민, 22=이강우}
{16=손흥민, 22=이강우}
[16, 22]
16번 손흥민
22번 이강우
Generic 01
=> Generic 클래스
// - 클래스의 멤버 변수, 메소드 또는 생성자의 매개변수, 메소드의 리턴 타입 등을
// 지정하지 않고, 일반적으로 정의하는 클래스
// - generic 클래스를 정의할 때 사용되는 일반화 변수(T)는 클래스 타입만 가능
// -> 자바의 기본 자료형(int, boolean, double, ..)을 사용할 수 없음
// -> 기본 자료형 대신에 wrapper 클래스를 일반화 변수로 사용
Box<T>
public class Box<T> {
private T content;
public Box(T content) {
this.content = content;
}
public T pullOut() {
return content;
}
} // end Box<T>
Apple
public class Apple {
private String type;
public Apple(String type) {
this.type = type;
}
public void displayAppleType() {
System.out.println("사과 품종 : " + type);
}
} // end Apple
AppleBox
public class AppleBox {
private Apple apple;
public AppleBox(Apple apple) {
this.apple = apple;
}
public Apple pullOut() {
return apple;
}
} // end AppleBox
Orange
public class Orange {
private int sugar;
public Orange(int sugar) {
this.sugar = sugar;
}
public void displayOrangeSugar() {
System.out.println("오렌지 당도 : " + sugar);
}
} // end Orange
OrangeBox
public class OrangeBox {
private Orange orange;
public OrangeBox(Orange orange) {
this.orange = orange;
}
public Orange pullOut() {
return orange;
}
} // end OrangeBox
Main
public class GenericMain01 {
public static void main(String[] args) {
Apple apple = new Apple("충주");
apple.displayAppleType();
AppleBox aBox = new AppleBox(apple);
aBox.pullOut().displayAppleType();
System.out.println();
Orange orange = new Orange(12);
OrangeBox oBox = new OrangeBox(orange);
oBox.pullOut().displayOrangeSugar();
System.out.println("==================");
// generic 클래스의 Box 인스턴스 생성
Box<Apple> box1 = new Box<Apple>(apple);
box1.pullOut().displayAppleType();
Box<Orange> box2 = new Box<Orange>(orange);
box2.pullOut().displayOrangeSugar();
Box<Integer> box3 = new Box<Integer>(123);
int a = box3.pullOut().intValue();
System.out.println(a);
} // end main()
} // end GenericMain01
출력
사과 품종 : 충주
사과 품종 : 충주
오렌지 당도 : 12
==================
사과 품종 : 충주
오렌지 당도 : 12
123
Generic 02
// 두 개 이상의 일반화 변수를 갖는 generic 클래스
class Test<T, U>{
private T item1;
private U item2;
public Test(T item1, U item2) {
this.item1 = item1;
this.item2 = item2;
}
public void display() {
System.out.println("아이템1 : " + item1);
System.out.println("아이템2 : " + item2);
} // end display()
} // end Test
public class GenericMain02 {
public static void main(String[] args) {
Test<Integer, Integer> test1 = new Test<>(111, 222);
test1.display();
System.out.println();
Test<Integer, String> test2 = new Test<>(100, "hello");
test2.display();
} // end main()
} // end GenericMain02
출력
아이템1 : 111
아이템2 : 222
아이템1 : 100
아이템2 : hello
'java > 학원수업' 카테고리의 다른 글
Java _ Lambda 14 (0) | 2020.12.06 |
---|---|
Java _ InnerClass 13 (0) | 2020.12.06 |
Java _ API 11 (0) | 2020.12.06 |
JAVA _ Interface 10 (0) | 2020.12.06 |
JAVA _ Inheritance 9 (0) | 2020.12.03 |