***** 1. 지금까지 배운 컬렉션 클래스의 특징에 대해서 설명하세요 .
C 특징
ㄴ L ArrayList/Vector/LinkedList/Stack,Queue,Deque/PriorityQueue
ㄴ S HashSet
M
2. 열거자와 반복자에 대해서 설명하세요.
- Enumeration (구) X
- Iterator (신) 예외발생
3. "tiger", "cat" , "Dog", "lion" 문자열을 ArrayList 컬렉션 클래스에 추가하고
대소문자 구분 없이 내림차순으로 정렬해서
반복자를 사용해서 출력하세요.
// "tiger", "cat" , "Dog", "lion"
// <E> == (E)lement == 요소
/*
ArrayList list = new ArrayList();
list.add("tiger");
list.add("cat");
list.add("Dog");
list.add("lion");
*/
//System.out.println( list.toString() );
// System.out.println( list );
String [] animals = { "tiger", "cat" , "Dog", "lion" };
List list = Arrays.asList(animals); // ArrayList
System.out.println( list );
// 대소문자 구분 X + 내림차순 정렬
// 대소문자 구분 O + 오름차순 정렬
// list.sort(null);
// 클래스 선언 + 객체 생성 => 익명클래스
// DescendingComaprator c = new DescendingComaprator();
// list.sort( c );
/*
list.sort(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
return -1 * s1.toUpperCase().compareTo( s2.toUpperCase() );
}
});
*/
// list.sort( (s1, s2) -> -1 * ((String) s1).toUpperCase().compareTo( ((String) s2).toUpperCase() ));
list.sort( String.CASE_INSENSITIVE_ORDER );
// 반복자 출력
Iterator ir = list.iterator();
while (ir.hasNext()) {
String animal = (String) ir.next();
System.out.println( animal );
}
class DescendingComaprator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
String s1 = null ;
if ( o1 instanceof String ) {
s1 = (String) o1;
}
String s2 = (String)o2;
return -1 * s1.toUpperCase().compareTo( s2.toUpperCase() );
}
}
4. 로또번호를 HashSet을 사용해서 출력하는 코딩을 하세요 .
public static void main(String[] args) {
// 9:45 제출
// [공지사항] 4/1 부터 대면 수업~
HashSet lotto = new HashSet(6);
fillLotto( lotto );
dispLotto( lotto );
} // main
private static void dispLotto(HashSet lotto) {
Iterator ir = lotto.iterator();
while (ir.hasNext()) {
int n = (int) ir.next();
System.out.printf("[%d]", n);
}
System.out.println();
}
private static void fillLotto(HashSet lotto) {
// Set 인터페이스를 구현한 컬렉션 클래스 : 중복 허용 X, 순서 유지 X
while( lotto.size() < 6 ) {
int n = (int)(Math.random()*45)+1 ;
System.out.println( n );
lotto.add ( n );
}
}
5. 게임횟수를 입력받아 로또 번호를 출력하는 코딩을 하세요 .
게임 횟수 입력 ? 3
1게임 : [17][9][4][15][16][38]
2게임 : [17][9][4][15][16][38]
3게임 : [17][9][4][15][16][38]
package days25;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오전 7:42:39
* @subject
* @content
*/
public class Ex01 {
public static void main(String[] args) {
// 9:45 제출
// [공지사항] 4/1 부터 대면 수업~
HashSet lotto = new HashSet(6);
fillLotto( lotto );
dispLotto( lotto );
} // main
private static void dispLotto(HashSet lotto) {
// 1. 정렬
// lotto.sort() X
// ArrayList lottoList = new ArrayList();
// lottoList.addAll(lotto);
// 11:01 수업 시작~
ArrayList lottoList = new ArrayList( lotto );
lottoList.sort(null);
// 2. 출력
Iterator ir = lottoList.iterator();
while (ir.hasNext()) {
int n = (int) ir.next();
System.out.printf("[%d]", n);
}
System.out.println();
}
private static void fillLotto(HashSet lotto) {
// Set 인터페이스를 구현한 컬렉션 클래스 : 중복 허용 X, 순서 유지 X
while( lotto.size() < 6 ) {
int n = (int)(Math.random()*45)+1 ;
// System.out.println( n );
lotto.add ( n );
}
}
} // class
package days25;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오전 7:42:39
* @subject 게임 횟수 입력...
* @content
*/
public class Ex01_02 {
public static void main(String[] args) {
// 순서 유지 O + 정렬 X + Set(중복허용 X) => 컬렉션 클래스
int gameNumber = 1;
Scanner scanner = new Scanner(System.in);
System.out.print("> 게임 횟수 입력 ? ");
gameNumber = scanner.nextInt(); // 3
// LinkedHashSet [] lottos = new LinkedHashSet[gameNumber];
ArrayList lottos = new ArrayList(gameNumber );
for (int i = 0; i < gameNumber; i++) {
LinkedHashSet lotto = new LinkedHashSet(6 );
fillLotto( lotto );
// lottos.addAll(lotto); // LinkedHashSet 객체
lottos.add(lotto); // LinkedHashSet 객체
}
// [26, 18, 37, 30, 20, 40, 42, 41, 20, 32, 7, 2, 8, 10, 21, 29, 42, 3]
// System.out.println( lottos );
/*
// dispLotto( lotto );
*/
for (int i = 0; i < gameNumber; i++) {
System.out.printf("%d 게임 : " , i +1 );
dispLotto( (LinkedHashSet)lottos.get(i) ); // 다운캐스팅.
}
} // main
private static void dispLotto(HashSet lotto) { // 업캐스팅.
ArrayList lottoList = new ArrayList( lotto );
lottoList.sort(null);
// 2. 출력
Iterator ir = lottoList.iterator();
while (ir.hasNext()) {
int n = (int) ir.next();
System.out.printf("[%d]", n);
}
System.out.println();
}
private static void fillLotto(HashSet lotto) {
while( lotto.size() < 6 ) {
int n = (int)(Math.random()*45)+1 ;
lotto.add ( n );
}
}
} // class
package days25;
import java.util.ArrayList;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오전 11:24:04
* @subject
* @content
*/
public class Ex02 {
public static void main(String[] args) {
ArrayList list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList list2 = new ArrayList();
list1.add(11);
list1.add(22);
list1.add(33);
ArrayList list3 = new ArrayList();
//list3.addAll(list1);
//list3.addAll(list2);
list3.add(list1);
list3.add(list2);
System.out.println( list3 ); // [1, 2, 3, 11, 22, 33]
}
}
package days25;
import java.util.Iterator;
import java.util.LinkedHashSet;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오전 11:35:04
* @subject
* @content
*/
public class Ex03 {
public static void main(String[] args) {
// [빙고 게임]
// 12:00 수업 시작~
int [][] bingo = new int[5][5];
// 숫자를 중복되지 않게 1~50 채워넣자.
/*
for (int i = 0; i < bingo.length; i++) {
for (int j = 0; j < bingo[i].length; j++) {
int n = (int)( Math.random()*50 ) + 1; // 중복 되지 않으면
if( ! isDuplicateCheck( bingo, i, j, n)) {
bingo[i][j] = n;
}else {
j--;
}
}
}
*/
LinkedHashSet set = new LinkedHashSet(25);
while ( set.size() < 25 ) {
int n = (int)( Math.random()*50 ) + 1;
set.add(n);
}
System.out.println( set );
// 1차원 -> 2차원 // 2차원 -> 1차원 // 2차원 -> 2차원
int i = 0;
Iterator ir = set.iterator();
while (ir.hasNext()) {
int n = (int) ir.next();
bingo[i/5][i%5] = n;
i++;
}
// 출력.
for ( i = 0; i < bingo.length; i++) {
for (int j = 0; j < bingo[i].length; j++) {
System.out.printf("[%02d]", bingo[i][j]);
}
System.out.println();
}
} // main
/*
private static boolean isDuplicateCheck(int[][] bingo, int i, int j, int n) {
for (int k = 0; k < i; k++) {
for (int k2 = 0; k2 < bingo[i].length; k2++) {
//
}
}
for (int k = 0; k < j; k++) {
//bingo[i][k] = n
}
return false;
}
*/
} // class
package days25;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 12:17:59
* @subject
* @content
*/
public class Ex04 {
public static void main(String[] args) {
// Set : 중복 허용 X, 순서 유지 X
Set<Student> sSet = new LinkedHashSet<>();
sSet.add( new Student("200101", "김동현", "26"));
sSet.add( new Student("200102", "김수민", "24"));
sSet.add( new Student("200103", "진예림", "25"));
sSet.add( new Student("200104", "심성환", "27"));
// 학번 같은 학생은 같은 객체로 인식해서 Set에 추가 되지 않도록 하자.
// hashCode() 메서드 + equals() 메서드를 학번이 같은 해쉬코드
// , 학번이 같으면 같다 equals() 오버라이딩.
sSet.add( new Student("200101", "김동현", "26"));
System.out.println( sSet.size() ); // 4.
// 학생 정보 출력.
// 약속) iterator() 반복자를 사용할 때 . 코딩할지 말고 복사해서 붙이고
// Ctrl + Shift + O
Iterator<Student> ir = sSet.iterator();
while (ir.hasNext()) {
Student s = ir.next();
System.out.printf("학번:%s, 이름:%s, 나이:%s\n", s.no, s.name, s.age);
}
} // main
} // class
class Student{
String no; // 학번 - 학생을 구분할 수 있는 고유한 필드
String name; // 학생명
String age; // 나이
public Student(String no, String name, String age) {
super();
this.no = no;
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return this.no.hashCode();
}
@Override
public boolean equals(Object obj) {
if ( obj instanceof Student) {
Student s = (Student)obj;
return this.no.equals(s.no);
}
return false;
}
}
@override는 Java와 같은 몇몇 프로그래밍 언어에서 사용되는 어노테이션(annotation)
상속받은 메서드를 재정의할 때, 부모 클래스의 메서드와 정확히 일치하는 이름, 매개변수, 반환 유형 등을 사용해야 한다는 것을 명시
public class Ex04_02 {
public static void main(String[] args) {
Student s1 = new Student("200101", "김동현", "26");
System.out.println( s1.hashCode() ); // 1521118594
Student s2 = new Student("200101", "김동현", "26");
// Student s2 = s1;
System.out.println( s2.hashCode() ); // 1940030785
System.out.println( s1.equals(s2) ); // 1940030785
}
}
package days25;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.stream.IntStream;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 12:41:14
* @subject
* @content
*/
public class Ex05 {
public static void main(String[] args) {
// int [] a = {1,2,3,4,5};
// int [] b = {4,5,6,7,8};
// 1) a U b 합집합 1,2,3,4,5,6,7,8
ArrayList a = new ArrayList();
a.add(1);a.add(2);a.add(3);a.add(4);a.add(5);
ArrayList b = new ArrayList();
b.add(4);b.add(5);b.add(6);b.add(7);b.add(8);
System.out.println(a);
System.out.println(b);
// a - b 차집합
HashSet cha = new HashSet();
HashSet kyo = new HashSet();
Iterator ir = a.iterator(); // [1, 2, 3, 4, 5]
while (ir.hasNext()) {
int aValue = (int ) ir.next();
if ( !b.contains(aValue )) cha.add(aValue);
else kyo.add(aValue);
}
System.out.println( "a - b : " + cha );
System.out.println( "a ∩ b : " + kyo );
/* 합집합 코딩. */
HashSet c = new HashSet();
c.addAll(a);
c.addAll(b);
System.out.println("a U b : " + c );
/*
int [] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.out.println( Arrays.toString(c ) );
// [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
// ↑
for (int i = 0, idx = a.length; i < b.length; i++) {
// c 배열 중복체크 b[i] X
}
*/
// 2) a - b 차집합 1,2,3
// 3) a ∩ b 교집합 4,5
} // main
} // class
package days25;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 2:17:31
* @subject
* @content
*/
public class Ex06 {
public static void main(String[] args) {
/* Set 인터페이스를 구현한 컬렉션 클래스 : HashSet
* [ TreeSet ]
* 1. 중복 허용 X, - 순서 유지할 필요 X
* 2. 이진 검색 트리를 사용해서 데이터 순서대로 저장한다.
* 3. 검색, 정렬, 범위 검색을 하는 데 뛰어난 성능을 보이는 컬렉션 클래스 이다.
* 4. 링크드리스트 처럼 노드(Node)가 서로 연결된 구조이다.
* 5. 최상위 노드를 "루트(root)노드"라고 한다.
* 부모 - 자식 노드 관계
* 형제 노드 관계
* 6. class TreeNode{
* TreeNode 왼쪽자식노드;
* Object value;
* TreeNode 오른쪽자식노드;
* 7. [ 이진 검색 트리 구조 ]
* 부모노드의 왼쪽에는 부모노드 값보다 작은 값의 자식노드를
* 오른쪽에는 " " 큰 값의 자식노드를 위치(배치)시킨다.
* 8. TreeSet도 Set 계열이기 때문에
* 중복 허용 X 때문에 저장되는 객체(값)가 Comparable 구현 또는 Comparator (비교기) 제공.
* }
* */
TreeSet<Integer> ts = new TreeSet<>();
ts.add(7);
ts.add(4);
ts.add(9);
ts.add(1);
ts.add(5);
ts.add(6);
// 추가한 순서대로 유지 X
// 오름차순 정렬
// [1, 4, 5, 6, 7, 9]
System.out.println( ts );
System.out.println( ts.first() ); // 정렬된 순서에서 첫 번째 값(객체)를 반환하는 메서드
System.out.println( ts.last() ); // 정렬된 순서에서 마지막 번째 값(객체)를 반환하는 메서드
SortedSet<Integer> ss = ts.subSet(1, 7);
System.out.println( ss ); // [1, 4, 5, 6]
// higher(1) : 지정된 값(객체==1)보다 큰 값을 가진 객체 중 제일 가까운 값의 객체를 반환
System.out.println( ts.higher(1) ); // 4
// System.out.println( ts.lower(1) ); // 4
// floor(3) : 지정된 값(3)과 같은 객체를 반환,
// 트리 구조에 3값이 없으면 작은 값을 가진 객체 중 제일 가까운 값을 반환.
// null 이 반환
System.out.println( ts.floor(3) ); // 1
//
System.out.println( ts.ceiling(3) ); // 4
} // main
} // class
package days25;
import java.util.TreeSet;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 2:48:22
* @subject
* @content
*/
public class Ex06_02 {
public static void main(String[] args) {
// 3:00 수업 시작~
TreeSet ts = new TreeSet();
ts.add("abc"); ts.add("alien"); ts.add("bat");
ts.add("car"); ts.add("Car"); ts.add("disc");
ts.add("dance"); ts.add("dzzz"); ts.add("dzzzz");
ts.add("elephant"); ts.add("elevator"); ts.add("fan");
ts.add("flower");
// 문자열 정렬~
System.out.println( ts );
// 범위 검색
System.out.println( ts.subSet("a", "d") ); // [abc, alien, bat, car]
System.out.println( ts.subSet("c", "dzzz") ); // [car, dance, disc]
}
}
package days25;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 3:06:14
* @subject
* @content
*/
public class Ex06_03 {
public static void main(String[] args) {
int [] score = { 80, 95, 50, 85, 45, 65, 10, 100 };
// [범위 검색]
// 75 점보다 큰 점수를 얻어와서 출력...
// 50점 보다 작은 점수를 얻어와서 출력..
// 50~75 점 범위
/*
TreeSet<Integer> ts = new TreeSet<Integer>();
for (int i : score) ts.add(i);
System.out.println( ts );
*/
// int [] -> ArrayList -> TreeSet 변환.
// stream() X
// boxed() X
// collect() X
// Collectors.toList() X
ArrayList<Integer> list =
(ArrayList<Integer>) Arrays.stream(score).boxed().collect(Collectors.toList());
// System.out.println( list );
TreeSet<Integer> ts = new TreeSet<Integer>(list);
System.out.println( ts );
// [10, 45, [ 50 ], 65, 80, 85, 95, 100]
SortedSet<Integer> ss = ts.headSet(50);
System.out.println( ss ); // [10, 45]
System.out.println( ts.tailSet(75) ); // [80, 85, 95, 100]
} // main
} // class
package days25;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 3:26:34
* @subject HashMap(신) 과 Hashtable( 구 )
* @content
*/
public class Ex07 {
public static void main(String[] args) {
/*
* 1. Map 인터페이스를 구현한 컬렉션 클래스
* 2. 키(key)와 값(value) 한 쌍으로 관리.
* 1) 엔트리( Entry )
* 2) 키(key) 중복 허용 X
* 값(value) 중복 허용 O
* 3. Vector와 ArrayList 관계와 비슷 ( 멀티 스레드 안전(== 동기화 처리 ))
* 4. Hash : 해싱이라는 기법을 사용하기 때문에 많은 양의 데이터를 검색할 때 성능이 뛰어난다.
* Tree 트리구조
*
* [해싱(Hashing)] ?
* - 해시함수( hash function)를 이용해서 데이터를 해시테이블(hash table)에 저장하고
* 검색하는 기법을 말한다.
* - 해시함수( hash function) 는 데이터가 저장되어 있느 곳을 알려 주기 때문에 다량의
* 데이터 중에서도 원하는 데이터를 빠르게 찾을 수 있다.
* - 해싱을 구현한 컬렉션 클래스 : HashSet, HashMap, Hashtable 등등
*
* 5. 가능하면 Hashtable 대신에 HashMap을 사용하자 ( 권장 )
* 6. 저장할 데이터( 키, 값)의 키를 해시함수에 넣으면 배열의 한 요소를 얻게 되고,
* 다시 그 곳에 연결되어 있는 링크드 리스트에 저장하게 된다.
*
* 예) 데이터(키,값)
* 2020.1.1 XXX
*
* [해시함수]
*
*
* [ 1999 ]
* [ ]
* [ ] [][][][][][][][][][]
* [ ] [][][][]
* -> [2020 ] 연결된 [1.1][][][][][][][][][][][][][][]
* [ ]
* [ ]
* [ ]
*
*
* */
// <E> Element 요소
// <T> Type 자료형
// <K Key, V Value >
HashMap<String, String> hm = new HashMap<>();
hm.put("kenik", "이창익"); // 엔트리( Entry )
hm.put("admin", "관리자");
hm.put("hong", "홍길동");
hm.put("root", "관리자"); // 값(Value) 은 중복 허용 O
hm.replace("root", "관리자", "새관리자");
System.out.println( hm.replace("hong", "홍길남") ); // oldValue 홍길동
System.out.println( hm.put("hong", "홍길강") ); // oldValue 홍길남
// [문제]
// key - value 형식으로 모든 엔트리를 출력.
// "kenik" - "이창익
// "kenik" - "이창익
// "kenik" - "이창익
// "root" - "관리자
// 1) 모든 키 - keySet() +// 2) get()
// java.util.Map.Entry<K, V>
// key + value = Entry
Set<Entry<String, String>> es =hm.entrySet();
Iterator<Entry<String, String>> ir = es.iterator();
while (ir.hasNext()) {
Entry<String, String> entry = ir.next();
String k = entry.getKey();
String v = entry.getValue();
System.out.printf( "%s - %s\n", k , v );
}
/*
Set<String> ks = hm.keySet();
Iterator<String> ir = ks.iterator();
while (ir.hasNext()) {
String k = (String) ir.next();
String v = hm.get(k);
System.out.printf( "%s - %s\n", k , v );
}
*/
// [문제] 모든 value 를 조회(출력) - values()
/*
Collection<String> vc = hm.values();
// System.out.println( vc );
Iterator<String> ir = vc.iterator();
while (ir.hasNext()) {
String v = (String) ir.next();
System.out.println( v );
}
*/
// hm 안에 있는 모든 key 를 조회. - keySet()
/*
Set<String> ks = hm.keySet();
Iterator<String> ir = ks.iterator();
while (ir.hasNext()) {
String k = (String) ir.next();
System.out.println( k );
}
*/
/*
// {hong=홍길동, kenik=이창익, root=관리자, admin=관리자}
// 키(key)은 중복 허용 X, 새로운 값(Value)로 설정되더라...
hm.put("admin", "이태규");
// 키(key)이 null 허용O,
hm.put( null, "박현주");
hm.put( null, null);
System.out.println( hm );
// "hong" 키가 존재하냐?
/*
hm.containsKey("");
hm.containsValue("");
System.out.println( hm.containsKey("hong") ); // true
System.out.println( hm.containsKey("park") ); // false
// admin 키가 존재하는 지 확인 후에 값(value)를 진예림으로 수정.
if ( hm.containsKey("admin") ) {
hm.put("admin", "진예림");
}
// "admin" 키의 값을 얻어와서 출력
// 4:05 수업 시작~
// hm.merge() // 병합
// String value = hm.get("admin");
// String value = hm.get("kkk");
// System.out.println( value ); // null
String value = hm.getOrDefault("kkk", "익명");
System.out.println( value);
// get() 와 getOrDefault() 메서드의 차이점.
// null , 2번째 매개변수값을 반환.
*/
}
}
;package days25;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 4:44:35
* @subject
* @content
*/
public class Ex08 {
public static void main(String[] args) {
// 파일 읽어와서 'A' 20 -> ####### 그래프
String fileName = "days20\\Ex01.java";
fileName = String.format("%s\\src\\%s"
, System.getProperty("user.dir")
, fileName );
// k + v = entry
// 'A' 1
// HashMap
// 5:00 수업 시작~
HashMap<Character, Integer> map = new HashMap<>();
char one = '\u0000';
int code = 0;
try (
FileReader fr = new FileReader(fileName);
){
while ( ( code = fr.read() ) != -1 ) {
one = (char) code;
// System.out.println( one );
if( map.containsKey( one ) ) { // 존재한다
int value = map.get(one);
map.put( one , value+1 );
}else { // 존재 X
map.put( one , 1);
}
} // while
// 막대그래프
// A(20) : ####################
Set<Entry<Character, Integer>> es = map.entrySet();
Iterator<Entry<Character, Integer>> ir = es.iterator();
while (ir.hasNext()) {
Entry<Character,Integer> entry = ir.next();
char key = entry.getKey();
int value = entry.getValue();
System.out.printf(" %c(%d) : %s\n",
key , value , "#".repeat(value)
);
}
} catch (Exception e) {
System.out.println( e.toString() );
}
} // main
} // class
;package days25;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 4:44:35
* @subject
* @content
*/
public class Ex08 {
public static void main(String[] args) {
// 파일 읽어와서 'A' 20 -> ####### 그래프
String fileName = "days20\\Ex01.java";
fileName = String.format("%s\\src\\%s"
, System.getProperty("user.dir")
, fileName );
// k + v = entry
// 'A' 1
// HashMap
// 5:00 수업 시작~
HashMap<Character, Integer> map = new HashMap<>();
char one = '\u0000';
int code = 0;
try (
FileReader fr = new FileReader(fileName);
){
while ( ( code = fr.read() ) != -1 ) {
one = (char) code;
// System.out.println( one );
if( map.containsKey( one ) ) { // 존재한다
int value = map.get(one);
map.put( one , value+1 );
}else { // 존재 X
map.put( one , 1);
}
} // while
// 막대그래프
// A(20) : ####################
Set<Entry<Character, Integer>> es = map.entrySet();
Iterator<Entry<Character, Integer>> ir = es.iterator();
while (ir.hasNext()) {
Entry<Character,Integer> entry = ir.next();
char key = entry.getKey();
int value = entry.getValue();
System.out.printf(" %c(%d) : %s\n",
key , value , "#".repeat(value)
);
}
} catch (Exception e) {
System.out.println( e.toString() );
}
} // main
} // class
;package days25;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author ♈ k§nik
* @date 2023. 3. 2. - 오후 4:44:35
* @subject
* @content
*/
public class Ex08 {
public static void main(String[] args) {
// 파일 읽어와서 'A' 20 -> ####### 그래프
String fileName = "days20\\Ex01.java";
fileName = String.format("%s\\src\\%s"
, System.getProperty("user.dir")
, fileName );
// k + v = entry
// 'A' 1
// HashMap
// 5:00 수업 시작~
HashMap<Character, Integer> map = new HashMap<>();
char one = '\u0000';
int code = 0;
try (
FileReader fr = new FileReader(fileName);
){
while ( ( code = fr.read() ) != -1 ) {
one = (char) code;
// System.out.println( one );
if( map.containsKey( one ) ) { // 존재한다
int value = map.get(one);
map.put( one , value+1 );
}else { // 존재 X
map.put( one , 1);
}
} // while
// 막대그래프
// A(20) : ####################
Set<Entry<Character, Integer>> es = map.entrySet();
Iterator<Entry<Character, Integer>> ir = es.iterator();
while (ir.hasNext()) {
Entry<Character,Integer> entry = ir.next();
char key = entry.getKey();
int value = entry.getValue();
System.out.printf(" %c(%d) : %s\n",
key , value , "#".repeat(value)
);
}
} catch (Exception e) {
System.out.println( e.toString() );
}
} // main
} // class
package days26;
public enum Direction {
EAST,
SOUTH,
WEST,
NORTH
}
1. 지금까지 배운 컬렉션 클래스의 특징에 대해서 설명하세요 .
TreeSet - [Set] + 이진트리구조 - 검색,범위검색,정렬
Hashtable/HashMap - 해싱기법 - 빠른 검색 Map
2. String fileName = "days25\\Ex01.java";
파일의 0-9, A-Z, a-z 각 문자의 갯수를 파악해서 출력하는 코딩을 하세요 .
HashMap<key ,value>
Character, Integer
파일 한 문자씩 읽어와서 읽어온 문자가 HashMap 객체의 키로 포함되어 있는지 유무를
체크해서 value를 1증가 시키는 코딩을....
문제점) 파일에 없는 문자는 HashMap에 엔트리로 포함되지 않았다. -> 출력 X
해결 ) 파일을 읽기 전에 미리 0-9, A-Z, a-z 이문자를 key로 value=0으로 엔트리 추가.
3. 1조, 2조, 3조 각 팀원들을 각각 ArrayList에 추가하고
그 각팀 ArrayList를 HashMap에 저장해서 iterator를 사용해서 출력하세요.
4. 코딩을 분석해서 주석을 달아주세요 .
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Sample {
// 그룹이름 이름 연락처
static HashMap<String, HashMap<String, String>> phoneBook = new HashMap<>();
public static void main(String[] args) {
// 12:05 소스분석 수업 시작~
String groupName, name, tel;
addPhoneNo( "친구","이자바","010-1111-1111" );
addPhoneNo( "친구","김자바","010-2222-2222" );
addPhoneNo( "친구","김자바","010-3333-3333" );
addPhoneNo( "회사","이대리","010-4444-4444" );
addPhoneNo( "회사","김대리","010-5555-5555" );
addPhoneNo( "회사","박대리","010-6666-6666" );
addPhoneNo( "동아리","김동아","010-7777-7777" );
addPhoneNo( null, "세탁소","010-8888-8888" );
addPhoneNo( null, "PC방","010-9999-8888" );
printList();
} // main
private static void printList() {
Set<Entry<String, HashMap<String, String>>> es = phoneBook.entrySet();
Iterator<Entry<String, HashMap<String, String>>> ir = es.iterator();
while (ir.hasNext()) {
Entry<String, HashMap<String, String>> entry =
(Entry<String, HashMap<String, String>>) ir .next();
String groupName = entry.getKey();
HashMap<String, String> groupMap = entry.getValue();
System.out.printf("* %s [%d]\n", groupName, groupMap.size() );
Iterator<Entry<String, String>> ir2 = groupMap.entrySet().iterator();
while (ir2.hasNext()) {
Entry<String, String> entry2 = (Entry<String, String>) ir2.next();
String name = entry2.getKey();
String tel = entry2.getValue();
System.out.printf("\t%s : %s\n", name, tel);
}
}
}
private static void addPhoneNo(String groupName, String name, String tel) {
groupName = groupName == null ? "기타" : groupName;
addGroup( groupName );
HashMap<String, String> group = phoneBook.get(groupName);
group.put(name, tel);
}
private static void addGroup(String groupName) {
if ( !phoneBook.containsKey(groupName) ) {
phoneBook.put(groupName, new HashMap<String, String>());
}
}
} // class
package days26;
public enum Direction {
EAST,
SOUTH,
WEST,
NORTH
}
package days26;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* @author ♈ kenik
* @date 2023. 3. 3. - 오전 8:36:14
* @subject
* @content
*
*/
public class Ex01 {
public static void main(String[] args) {
String [] 팀1 = { "이태규", "김지은", "설경인", " 윤재민", "홍성철", "김동현", "박상범", "이예진" };
String [] 팀2 = { "하동호", "박진용", "이혜진", "김수민", "신희민", "진예림", "박현주" };
String [] 팀3 = { "박민종", "심성환", "이진우", "홍찬기", "김예지", "하지예", "탁인혁" };
// 1) 각 팀원들을 ArrayList 객체에 요소로 저장을 했습니다.
ArrayList<String> team1 = new ArrayList<String>();
for (int i = 0; i < 팀1.length; i++) team1.add( 팀1[i] );
System.out.println( team1 ); // [이태규, 김지은, 설경인, 윤재민, 홍성철, 김동현, 박상범]
// String[] -> List -> ArrayList 변환
// Arrays 클래스의 asList() 메서드
List<String> temp = Arrays.asList(팀2);
ArrayList<String> team2 = new ArrayList<String>(temp);
System.out.println( team2 );
ArrayList<String> team3 = new ArrayList<String>( Arrays.asList(팀3) );
System.out.println( team3 );
// 10:15 수업 시작~
// 2) HashMap 각 팀을 엔트리로 저장.
HashMap<String, ArrayList<String>> class5Map = new HashMap<>();
class5Map.put("연봉1조", team1);
class5Map.put("귀염2(이)조", team2);
class5Map.put("자바를 잡아", team3);
printMap( class5Map );
} // main
private static void printMap( HashMap<String, ArrayList<String>> class5Map) {
// 1조_연봉1조(7명)
// ㄴ
// 2조_귀염2(이)조(7명)
// ㄴ
// 3조_자바를 잡아(8명)
// ㄴ
// ㄴ
// ㄴ
// ㄴ
Set<Entry<String, ArrayList<String>>> es = class5Map.entrySet();
Iterator<Entry<String, ArrayList<String>>> ir = es.iterator();
int n = 1;
while (ir.hasNext()) {
Entry<String, ArrayList<java.lang.String>> entry = ir.next();
String key = entry.getKey(); // 팀명
ArrayList<String> value = entry.getValue();
// int count = value.size();
System.out.printf("%d조_%s(%d명)\n", n++, key, value.size() );
Iterator<String> ir2 = value.iterator();
while (ir2.hasNext()) {
String name = ir2.next();
System.out.printf("\t\tㄴ %s\n", name);
}
} // while
}
} // class
package days26;
import days17.Employee;
import days17.Regular;
import days17.SalesMan;
public class Ex02 {
public static void main(String[] args) {
// 자식 객체 생성해서 부모 클래스에 참조시킬 수 있다 : 업캐스팅
Employee r1 = new Regular();
test( r1 );
SalesMan s1 = new SalesMan();
test( s1 );
String name = "홍길동";
System.out.println( name );
}
// 업캐스팅
// 매개변수 다형성
public static void test( Employee emp ) {
//
}
}
public class Ex03 {
// 11:15 수업 시작~
// key value
// key value
// 연락처_북
// 그룹명
static HashMap<String, HashMap<String, String>> phoneBook = new HashMap<>();
public static void main(String[] args) {
// 그룹명 이름 연락처
String groupName, name, tel;
addPhoneNo( "친구","이자바","010-1111-1111" );
// 친구 HashMap<String, String> <-이자바","010-1111-1111"
addPhoneNo( "친구","김자바","010-2222-2222" );
// 친구 HashMap<String, String> <-이자바","010-1111-1111"
// 친구 HashMap<String, String> <-김자바","010-2222-2222"
addPhoneNo( "친구","김자바","010-3333-3333" );
addPhoneNo( "회사","이대리","010-4444-4444" );
addPhoneNo( "회사","김대리","010-5555-5555" );
addPhoneNo( "회사","박대리","010-6666-6666" );
addPhoneNo( "동아리","김동아","010-7777-7777" );
addPhoneNo( null, "세탁소","010-8888-8888" ); // 기타
addPhoneNo( null, "PC방","010-9999-8888" ); // 기타
printList();
} // main
private static void printList() {
Set<Entry<String, HashMap<String, String>>> es = phoneBook.entrySet();
Iterator<Entry<String, HashMap<String, String>>> ir = es.iterator();
while (ir.hasNext()) {
Entry<String, HashMap<String, String>> entry =
(Entry<String, HashMap<String, String>>) ir .next();
String groupName = entry.getKey();
HashMap<String, String> groupMap = entry.getValue();
System.out.printf("* %s [%d]\n", groupName, groupMap.size() );
Iterator<Entry<String, String>> ir2 = groupMap.entrySet().iterator();
while (ir2.hasNext()) {
Entry<String, String> entry2 = (Entry<String, String>) ir2.next();
String name = entry2.getKey();
String tel = entry2.getValue();
System.out.printf("\t%s : %s\n", name, tel);
}
}
}
// addPhoneNo( "동아리","김동아","010-7777-7777" );
// 그룹명 이름 연락처
private static void addPhoneNo(String groupName, String name, String tel) {
groupName = ( groupName == null ? "기타" : groupName );
addGroup( groupName ); // key 그룹명, value HashMap<String, String>
HashMap<String, String> group = phoneBook.get(groupName);
group.put(name, tel);
}
private static void addGroup(String groupName) {
if ( !phoneBook.containsKey(groupName) ) {
phoneBook.put(groupName, new HashMap<String, String>());
}
}
} // class
public class Ex04 {
public static void main(String[] args) {
// HashMap(신)-권장 , Hashtable X( 구 )
// 동기화 처리
// Tree[Map] -- Tree[Set]
// 1) key + value = Entry 데이터를 저장하는 컬렉션 클래스
// 2) Tree : 이진 검색 트리 형태로 데이터를 저장하는 컬렉션 클래스
// 3) 검색, 부분 검색, 정렬 성능이 빠르다.
// SortedMap<K, V>
// 1) Map key + value = Entry 데이터를 저장하는 컬렉션 클래스
// 2) Sorted : 정렬된 맵
TreeMap<String, String> tm = new TreeMap<String, String>();
// tm.
} // main
} // class
package days26;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Hashtable;
import java.util.Properties;
/**
* @author ♈ kenik
* @date 2023. 3. 3. - 오전 11:35:53
* @subject Properties 컬렉션 클래스 *****
* @content
* 1) Hashtable의 자식 클래스이다.
* 2) Map key + value=Entry
* 3) String String
* 4) 환경설정( 설정정보 )
* 속성(Property) = 속성값
*/
public class Ex05 {
public static void main(String[] args) {
//Hashtable<String, String> ht;
//Properties p;
// JAVA + 오라클DB 연동 + CRUD 작업
// DB 연결 설정 정보
String className = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "scott";
String password = "tiger";
// 1. 위의 DB 연결하기 위한 설정 정보들을 Properties 컬렉션에 저장
Properties p = new Properties();
// p.put(key, value);
// p.setProperty(key, value); O 권장.
p.setProperty("className","oracle.jdbc.driver.OracleDriver" );
p.setProperty("url", "jdbc:oracle:thin:@localhost:1521:xe");
p.setProperty("user", "scott");
p.setProperty("password", "tiger");
// { password=tiger, className=oracle.jdbc.driver.OracleDriver,
// user=scott , url=jdbc:oracle:thin:@localhost:1521:xe}
System.out.println( p );
// value = p.get( key );
String value = p.getProperty("url");
System.out.println( value );
// 2. Properties 객체에 있는 설정정보를 파일(jdbc.properties )로 다시 저장
// 확장자( .properties) 라면 Properties 컬렉션 객체에서 사용하는 파일이다..
// 파일 쓰기(저장 ) : FileWriter
// 파일 읽기(열기) : FileReader
/*
String fileName = ".\\src\\com\\util\\jdbc.properties";
String comments = "[comments]";
try ( FileWriter writer = new FileWriter(fileName)){
p.store(writer, comments ); // 파일 저장
System.out.println(" Save END");
} catch (Exception e) {
e.printStackTrace();
}
*/
// p.list(System.out);
// 12:15 수업 시작~
// xml 파일(.xml) 로 저장
/*
String fileName = ".\\src\\com\\util\\jdbc.xml";
String comments = "[comments]";
try ( FileOutputStream os = new FileOutputStream(fileName) ){
p.storeToXML(os, comments, "UTF-8"); // XML파일 저장.
System.out.println(" Save END");
} catch (Exception e) {
e.printStackTrace();
}
*/
// 3. 파일 -> Properties 객체를 사용해서 읽어와서 사용.
} // main
} // class
public class Ex05_02 {
public static void main(String[] args) {
String fileName = ".\\src\\com\\util\\jdbc.properties";
Properties p = new Properties(); // Hashtable 자식 클래스 (Map)
try( FileReader reader = new FileReader(fileName) ) {
p.load(reader);
// list() 메서드
// p.list( System.out );
System.out.println( p.getProperty("password") );
System.out.println( p.getProperty("url") );
System.out.println( p.getProperty("user") );
System.out.println( p.getProperty("className") );
} catch (Exception e) {
e.printStackTrace();
}
} // main
} // class
public class Ex05_03 {
public static void main(String[] args) {
// C:\Class\WorkSpace\JavaClass\javaPro
/*
String dir = System.getProperty("user.dir");
System.out.println( dir );
*/
Properties p = System.getProperties();
/*
p.propertyNames();
p.keys();
p.keySet();
*/
Enumeration<String> en = (Enumeration<String>) p.propertyNames();
while (en.hasMoreElements()) {
String key = en.nextElement();
System.out.printf("%s - %s\n", key, p.getProperty(key) );
}
} // main
} // class
public class Ex06 {
public static void main(String[] args) {
// Arrays 클래스 - fill(), copy(), sort(), binarySearch() 등등
// Collections 클래스
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println( list ); // []
// 1. Collection <? super T> c
Collections.addAll(list, 1,2,3,4,5);
System.out.println( list ); // [1, 2, 3, 4, 5]
// 2. 오른쪽으로 2칸 이동
//Collections.rotate(list, 2);
//System.out.println( list ); // [4, 5, 1, 2, 3]
// 3. 첫번째 요소와 세번째 요소를 교환(swap)
//Collections.swap(list, 0, 2);
//System.out.println( list ); // [3, 2, 1, 4, 5]
// 4. 임의의 위치로 변경
Collections.shuffle(list);
System.out.println(list); // [3, 4, 1, 5, 2], [3, 2, 5, 1, 4]
// 5. 오름차순 정렬
// 내림차순 정렬
//Collections.sort(list);
Collections.sort(list, Collections.reverseOrder());
// Collections.reverse(list);
System.out.println( list ); // [1, 2, 3, 4, 5]
// Collections.fill(list, 9);
// Collections.copy(list, newList);
// Collections.replaceAll(list, oldValue, newValue)
// 등등
// Arrays 클래스 사용..
// Collections 클래스
}
}
public class Ex07 {
public static void main(String[] args) {
/* [ 제네릭( Generics ) ]
* 1. JDK 1.5 추가
* JDK 1.8 추가 - 람다식.
* 2. 제네릭이란 ? 다양한 타입의 객체를 다루는 메서드 , 컬렉션 클래스 에서....
* 컴파일 시의 타입(자료형) 체크를 해주는 기능.
* 3. 제네릭의 장점
* 1) 타입의 안정성을 제공
* 2) 타입 체크와 형변환을 생략할 수 있다.( 코드가 간결해진다.)
*
* */
/*
ArrayList list = new ArrayList();
list.add("홍길동") ; // String
list.add(20); // int
list.add( true ); // boolean
list.add( 'A'); // char
String name = (String) list.get(0); // "홍길동"
System.out.println( name );
int age = (int) list.get(1);
System.out.println( age );
*/
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
// list.add("Hong"); 1) 장점 : 타입의 안정성 제공
int age = list.get(0); // 2) 장점 : 형변환 X
System.out.println( age);
} // main
} // class
public class Ex07_02 {
public static void main(String[] args) {
/*
* 4. 제네릭 클래스 선언
* */
/*
Box box = new Box();
// 1. int
// box.setItem(100);
// 2. String
// box.setItem("홍길동");
// 3. double
// box.setItem(3.14);
// 4. char 'A'
// box.setItem('A');
System.out.println( box.getItem() ); // 다운캐스팅..( 불편한 점 )
*/
// String 대입된 타입( 매개변수화된 타입)
// Box<String> 제네릭 타입 호출
Box<String> box = new Box<String>();
box.setItem("홍길동");
String name =box.getItem();
System.out.println( name );
Box<Integer> box2 = new Box<Integer>();
box2.setItem(100);
int age = box2.getItem();
System.out.println( age );
} // main
} // class
// [ 제네릭 클래스 ] 선언 - 컴파일 시에 타입이 결정된다.
// T 타입 변수 또는 타입 매개변수
// Box 원시 타입( raw type )
// Box<T> 제네릭 클래스
class Box<T>{ // 클래스명 옆에 <T>을 부티이면 된다.
private T item;
public T getItem() {
return item;
}
public void setItem(T item) {
this.item = item;
}
}
/*
class Box{
private Object item;
public Object getItem() {
return item;
}
public void setItem(Object item) {
this.item = item;
}
}
*/
/*
class Box{
private int item;
public int getItem() {
return item;
}
public void setItem(int item) {
this.item = item;
}
}
*/
/*
class Box{
private String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
*/
/*
class Box{
private double item;
public double getItem() {
return item;
}
public void setItem(double item) {
this.item = item;
}
}
*/
/*
class Box{
private char item;
public char getItem() {
return item;
}
public void setItem(char item) {
this.item = item;
}
}
*/
public static void main(String[] args) {
/*
* 5. 제네릭스의 제한
* 1) 객체별로 다른 타입으로 지정해서 동작하도록 만든 기능이기 때문에
* static 필드는 선언할 수 없다.
* 2) static 메서드의 매개변수 타입으로 T를 사용할 수 없다.
* 3) T 타입의 배열 선언할 수 있다.
* 4)
* */
} // main
} // class
class Box02<T>{
// static T item2; static 필드는 제네렉 클래스에 선언할 수 없다.
// static int comapre( T t1, T t2 ) { // static 메서드의 매개변수 타입으로 T를 사용할 수 없다.
// }
T[] itemArr; // T 타입의 배열 선언할 수 있다.
T[] toArray() {
// T[] tmpArr = new T[itemArr.length]; // 제네릭 배열 생성 불가. instanceof X new X
// newInstance() 메서드로 동적 생성 가능하다.
// return tmpArr;
return null;
}
private T item;
public T getItem() {
return item;
}
public void setItem(T item) {
this.item = item;
}
public class Ex07_04 {
public static void main(String[] args) {
/*
* 6. 제네릭 클래스의 객체 생성과 사용.
* 3:16 수업 시작~~~
* */
/*
Box03<Fruit> fruitBox = new Box03<Fruit>();
Box03<Apple> appleBox = new Box03<Apple>();
Box03<Grape> grapeBox = new Box03<Grape>();
Box03<Toy> toyBox = new Box03<Toy>();
// Type mismatch: cannot convert from Box03<Grape> to Box03<Apple>
// Box03<Apple> box1 = new Box03<Grape>(); // 에러 발생.
fruitBox.add( new Fruit() ); // 과일 객체
fruitBox.add( new Apple() ); // 사과객체
fruitBox.add( new Grape() ); // 포함객체
// The method add(Fruit) in the type Box03<Fruit> is not applicable for the arguments (Toy)
// fruitBox.add( new Toy() ); // 장난감객체 에러
toyBox.add(new Toy() );
// toyBox.add(new Apple() ); // 에러
*/
} // main
} // class
/*
// Fruit
// ㄴ Apple
// ㄴ Grape
// Toy
class Fruit{ public String toString() { return "Fruit"; } }
class Apple extends Fruit{ public String toString() { return "Apple"; } }
class Grape extends Fruit{ public String toString() { return "Grape"; } }
class Toy{ public String toString() { return "Toy"; } }
// 제네릭 클래스 선언
class Box03<T>{
ArrayList<T> list = new ArrayList<T>();
void add(T item) { this.list.add(item); }
T get(int i) { return this.list.get(i); }
int size() { return this.list.size(); }
public String toString(){ return this.list.toString(); }
}
*/
public class Ex07_05 {
public static void main(String[] args) {
/*
* 7. 제한된 제네릭 클래스
* */
/*
FruitBox<Apple> appleBox = new FruitBox<Apple>();
appleBox.add( new Apple() );
appleBox.add( new Apple() );
appleBox.add( new Apple() );
// appleBox.add( new Grape() ); // 포도 에러
FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
fruitBox.add( new Apple() );
fruitBox.add( new Grape() );
*/
//[ 문제점 ]
// FruitBox 제네릭 클래스 선언할 때 - 과일만 담을 수 있는 상자..
// FruitBox 제네릭 클래스 에는 장남감(Toy)는 담을 수 없는 제네릭 클래스로 제한...
// <T exntes Fruit> 타입 제한하고 나면 Toy는 T(타입)으로 사용할 수 없다.
/*
FruitBox<Toy> toyBox = new FruitBox<Toy>();
toyBox.add( new Toy() );
*/
} // main
} // class
/*
interface Eatable { }
class Fruit implements Eatable{ public String toString() { return "Fruit"; } }
class Apple extends Fruit{ public String toString() { return "Apple"; } }
class Grape extends Fruit{ public String toString() { return "Grape"; } }
class Toy{ public String toString() { return "Toy"; } }
// 상자 - 과일/장난감 .. 여러 타입의 객체를 담을 수 있는 상자.
class Box04<T>{
ArrayList<T> list = new ArrayList<T>();
void add(T item) { this.list.add(item); }
T get(int i) { return this.list.get(i); }
int size() { return this.list.size(); }
public String toString(){ return this.list.toString(); }
}
*/
// 과일만 담을 수 있는 상자..
/*
class FruitBox<T> extends Box04<T>{
// 구현
}
*/
// <T extends Fruit> 의미는 모든 타입(T)가 아니라 Fruit 클래스의 자식들만 T로 사용하도록
// 제한합니다.
/*
class FruitBox<T extends Fruit> extends Box04<T>{
// 구현
}
*/
// Eatable 인터페이스 이지만 implements 를 사용하지 않고 extends 키워드를 사용한다.
/*
class FruitBox<T extends Eatable> extends Box04<T>{
// 구현
}
*/
// Eatable 인터페이스도 구현되고 Fruit 클래스 자식도 만족해야 만 T 타입으로 사용할
// 할 수 있다고 제한..
/*
class FruitBox<T extends Fruit & Eatable> extends Box04<T>{
// 구현
}
*/
public class Ex07_06 {
public static void main(String[] args) {
/*
* 8. 와일드 카드 ( ? )
* <? extends T> 와일드 카드의 상한 제한. T의 자손만 가능
* <? super T> 와일드 카드의 하한 제한. T의 조상만 가능
* <?> 제한 없음. <? extends Object> 동일한 의미
* */
FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
Juice juice = Juicer.makeJuice(fruitBox);
System.out.println( juice ); // days26.Juice@69222c14
FruitBox<Apple> appleBox = new FruitBox<Apple>();
juice = Juicer.makeJuice(appleBox);
System.out.println( juice ); // days26.Juice@69222c14
FruitBox<Grape> grapeBox = new FruitBox<Grape>();
juice = Juicer.makeJuice(grapeBox);
System.out.println( juice ); // days26.Juice@69222c14
} // main
} // class
// 과일 클래스
class Fruit { public String toString() { return "Fruit"; } }
// 사과 클래스
class Apple extends Fruit{ public String toString() { return "Apple"; } }
// 포도클래스
class Grape extends Fruit{ public String toString() { return "Grape"; } }
// 4:05 수업 시작~~
// 과일/사과/포도 -> 과일박스를 매개변수로 쥬스만들어서 반환하는 Juicer 라는 클래스 선언.
// static makeJuice() 메서드 선언
class Box05<T>{
ArrayList<T> list = new ArrayList<T>();
void add(T item) { this.list.add(item); }
T get(int i) { return this.list.get(i); }
int size() { return this.list.size(); }
public String toString(){ return this.list.toString(); }
}
class FruitBox<T extends Fruit> extends Box05<T>{
// 구현
}
// 쥬스를 만드는 기기
class Juicer{
static Juice makeJuice( FruitBox<? extends Fruit> box ) {
//
//
return new Juice();
}
// 위의 메서드를 "제네릭 메서드"로 선언...
// 리턴 자료형 앞에 <T> 타입변수를 선언한다.
// 제네릭클래스의 <T>와는 별개 X
/*
static <T extends Fruit> Juice makeJuice( FruitBox<T> box ) {
//
//
return new Juice();
}
*/
// 오버로딩.... ( 중복함수 )
/*
static Juice makeJuice( FruitBox<Fruit> box ) {
//
//
return new Juice();
}
static Juice makeJuice( FruitBox<Apple> box ) {
//
//
return new Juice();
}
static Juice makeJuice( FruitBox<Grape> box ) {
//
//
return new Juice();
}
*/
}
// 쥬스클래스
class Juice{
// 구현
}
public class Ex07_07 {
public static void main(String[] args) {
/*
* 9. 제네릭 메서드
* - 메서드의 선언부에 제네릭 타입이 선언된 메서드를 제네릭 메서드라고 한다.
*
* Ex07_06의 메서드를 제네릭메서드로 선언..
static <T extends Fruit> Juice makeJuice( FruitBox<T> box ) {
//
//
return new Juice();
}
[ Ex07_06.java ]
FruitBox<Apple> appleBox = new FruitBox<Apple>();
juice = Juicer.makeJuice(appleBox);
System.out.println( juice ); // days26.Juice@69222c14
[제네릭 메서드로 선언하고 나면 호출방법이 다르다. ]
FruitBox<Apple> appleBox = new FruitBox<Apple>();
juice = Juicer.<Apple>makeJuice(appleBox);
juice = Juicer.makeJuice(appleBox); // 생략 가능
System.out.println( juice ); // days26.Juice@69222c14
* */
} // main
} // class
public class Ex07_07 {
public static void main(String[] args) {
/*
* 9. 제네릭 메서드
* - 메서드의 선언부에 제네릭 타입이 선언된 메서드를 제네릭 메서드라고 한다.
*
* Ex07_06의 메서드를 제네릭메서드로 선언..
static <T extends Fruit> Juice makeJuice( FruitBox<T> box ) {
//
//
return new Juice();
}
[ Ex07_06.java ]
FruitBox<Apple> appleBox = new FruitBox<Apple>();
juice = Juicer.makeJuice(appleBox);
System.out.println( juice ); // days26.Juice@69222c14
[제네릭 메서드로 선언하고 나면 호출방법이 다르다. ]
FruitBox<Apple> appleBox = new FruitBox<Apple>();
juice = Juicer.<Apple>makeJuice(appleBox);
juice = Juicer.makeJuice(appleBox); // 생략 가능
System.out.println( juice ); // days26.Juice@69222c14
* */
} // main
} // class
public class Ex08 {
public static void main(String[] args) {
/*
* [ 열거형( enums ) ]
* - 서로 관련된 상수를 편리하게 선언하기 위한 것.
* - JDK 1.5 추가.
*
* - 열거형 선언 형식
* enum 열거형이름 { 상수명1, 상수명2, ... }
*
* - 열거형의 조상은 java.lang.Enum 클래스이다.
*
* - 열거형을 사용하는 방법.
* 열거형이름.상수명
* */
System.out.println( Direction.EAST ); // EAST
System.out.println( Direction.EAST.name() ); // 열거형 상수의 이름을 문자열로 반환하는 메서드
System.out.println( Direction.EAST.ordinal() ); // 열거형 상수가 정의된 순서를 반환하는 메서드 0
// valueOf() 메서드
Direction d = Direction.valueOf("WEST");
System.out.println( d );
// values()
Direction [] m = Direction.values();
System.out.println( Arrays.toString( m ) ); // [EAST, SOUTH, WEST, NORTH]
// 7명의 팀원 프로젝트 진행...
// 성별 남자/여자 코딩...
// true/false
// 1 / 0
// 'm' / 'f'
// "남자"/"여자"
// 등등
// Calendar.YEAR == 1
} // main
} // class
enum Card { CLOVER, HEART, DIAMOND, SPADE }
'-java spring notes- > JAVA' 카테고리의 다른 글
list 배열, for문,vo (0) | 2023.09.18 |
---|---|
Day-20 정규표현식, 캘린더 (0) | 2023.03.10 |
Day19 - 예외 (0) | 2023.03.10 |
day18-객체+예외처 (0) | 2023.03.06 |
객체 복습-day15~day18(자바의정석 기초 객체1+참고소스 복습~this) (1) | 2023.02.21 |