오늘의 과정 목록
- java.lang 패키지
(String, StringBuilder, StringBuffer 클래스 | Wrapper 클래스 | Math 클래스 | System 클래스)- java.util 패키지
(Collection Framework | List, Set, Map 인터페이스 | Iterator 날짜와 시간 처리에 대한 클래스 | Random 클래스
java.lang 패키지
String, StringBuilder, StringBuffer 클래스 이해하기
String str = "Hello, ";
str += "World!";
System.out.println(str);
/*
출력 결과)
HelloWorld!
*/
StringBuilder sb = new StringBuilder("Hello, ");
sb.append("World!");
System.out.println(sb);
/*
출력 결과)
Hello, World!
*/
Wrapper 클래스
기본형 데이터 타입을 참조형 데이터 타입으로 다루고자 할 때 사용할 수 있는 클래스이다.
자바의 기본 타입은 객체를 다루지 않기 때문에 자바에서 클래스만 요구할 때 기본형데이터 타입을 사용할 수 없으니 참조할 수 있도록 돕는다.
각 기본형 타입마다 참조형 타입의 클래스가 존재한다.
byte -> Byte | short -> Short | int -> Integer | long -> Long
float -> Float | double -> Double
char -> Character
boolean -> Boolean
장점
기본형데이터 타입에 넣을 수 없는 데이터를 참조형 데이터 타입에 넣을 수 있다.
null값을 받아야 하는 상황에서 Interger(Wrapper)을 사용하는게 좋다.
단점
유용하게 쓰이지만 인스턴스 메서드가 있는 만큼 그 만큼의 메모리 공간을 차지해 버린다.
숫자만 쓴다면 Wrapper를 사용하지 않는 것이 바람직하다.
// 이전에는 클래스이기 때문에 아래와 같이 생성자를 만들어야 했다.
Integer integer1 = new Integer(100);
// 정수 다루듯이 다룰 수 있다.
Integer integer2 = 100;
Double double2 = 3.1488888;
// Integer 값에 저장된 주소값을 들고온 것.
int int1 = integer1;
double double3 = double2;
// 숫자 100이 문자열 100으로 출력됨. 눈에 보이기에는 숫자 100으로 보이지만 문자열이다.
String string1 = integer1.toString();
System.out.println(string1);
int int2 = Integer.parseInt(string1); // 문자열을 정수로 바꿈.
System.out.println(int2); // 숫자 정수 100으로 변환..
/*
출력 결과)
100
100
*/
Math 클래스
Math 클래스의 메서드
Math 클래스의 상수
Double double2 = 3.1488888;
double double3 = double2;
// 반올림
System.out.println(Math.round(double3));
System.out.println(Math.round(double3 * 100) / 100.0);
/*
출력 결과)
3
3.15
*/
System 클래스
System 클래스의 주요 필드
System 클래스의 주요 메서드
java.util 패키지
Collection Framework
- 데이터를 저장하는 구조를 제공하는 표준화된 인터페이스 및 클래스이다
- 저장, 검색, 수정, 삭제에 대한 기능을 제공해준다.
- List, Set, Map, Queue, Stack
- 이 중에서 List, Set, Map을 주로 사용한다.
+ Collection과 Collections의 차이
- Collection은 인터페이스로, 여러 데이터를 저장하는데 사용되는 구조의 상위 형태입니다. List, Set, Queue 등이 Collection 인터페이스를 구현한다.
- Collections는 유틸리티 클래스로, 정렬(sort), 반전(reverse), 탐색(search) 등의 기능을 제공한다.
List 인터페이스
1) ArrayList 구현체
// List<Integer> arrayList; : 변수에 배열을 담을 수 있는 참조변수이기 때문에 생성자가 필요하다.
List<Integer> arrayList = new ArrayList<Integer>(); // : [] - 배열이 만들어 짐
// list에 데이터 추가 - add(); (add메서드)
arrayList.add(10); // : [10]
arrayList.add(12); // : [10, 12]
arrayList.add(1, 13); // : [10, 13, 12]
// arrayList.add("10"); - Integer 타입이기 때문에 문자열 불가.
System.out.println(arrayList);
// list에 요소 불러오기 - get();
System.out.println(arrayList.get(2));
// System.out.println(arrayList.get(4)); - 인덱스 자리를 벗어남 (java.lang.IndexOutOfBoundsException)
// list에 요소 수정하기 - set();
arrayList.set(1, 100); // : [10, 100, 12]
System.out.println(arrayList);
// arrayList.set(4, 100); - java.lang.IndexOutOfBoundsException
// System.out.println(arrayList);
// list에 요소 삭제하기 - remove();
// 요소 자체를 지정할 수 있다.
arrayList.remove(0); // : [100, 12]
System.out.println(arrayList);
// arrayList.remove(100); - java.lang.IndexOutOfBoundsException
// System.out.println(arrayList);
Integer element = 100; // int를 Integer인지 구별을 못해 바꾸어줌.
arrayList.remove(element); // : [12]
System.out.println(arrayList);
/*
출력 결과)
[10, 13, 12]
12
[10, 100, 12]
[100, 12]
[12]
*/
2) LinkedList 구현체
List<Integer> linkedList = new LinkedList<Integer>();
Set 인터페이스
1) HashSet
Set<Integer> hashSet = new HashSet<Integer>(); // 일반적인 방법.
// HashSet<Integer> hashSet = new HashSet<Integer>(); // 이렇게 써도 상관은 없다.
// set에 데이터 추가 - add();
// 읽기와 수정이 불가능하다.
hashSet.add(99);
hashSet.add(77);
// hashSet.add(1,0); // 순서가 없기 때문에 특정 인덱스에 추가되지 않는다.
hashSet.add(99); // 99는 중복되기 때문에 추가하지 않는다.
System.out.println(hashSet);
// set에 데이터 존재 여부 - contains(); (true인지, false인지 알려준다)
System.out.println(hashSet.contains(99));
// set에서 데이터 삭제 - remove();
hashSet.remove(99); // 인덱스가 존재하지 않기 때문에 요소로 지울 수 있다
System.out.println(hashSet);
// set에 구조의 사이즈 확인 - size();
System.out.println(hashSet.size()); // 요소의 개수, 사이즈 길이.
/*
출력 결과)
[99, 77]
true
[77]
1
*/
2) LinkedHashSet
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>();
3) TreeSet
Set<Integer> treeSet = new TreeSet<Integer>();
treeSet.add(99);
treeSet.add(77);
System.out.println(treeSet);
/*
[77, 99]
*/
Map 인터페이스
1) HashMap 구현체
Map<String, String> hashMap = new HashMap<>();
// map에 데이터 추가 - put();
hashMap.put("banana", "바나나"); // {banana=바나나}
hashMap.put("apple", "사과"); // {banana=바나나, apple=사과}
hashMap.put("apple", "사과1"); // {banana=바나나, apple=사과1}
System.out.println(hashMap);
// map에 데이터 읽기 - get();
// - 순서가 없어 인덱스를 넣지 않는다.
// - 존재하지 않는 키를 넣으면 null이 나온다.
System.out.println(hashMap.get("apple"));
System.out.println(hashMap.get("apple1"));
// map에 키 존재 여부 - containsKey();
// - true, false로 출력
System.out.println(hashMap.containsKey("apple"));
// map에 데이터 삭제 - remove();
// - 지우는게 아니라 있는 것을 빼는 것으로.
// hashMap.remove("apple");
// System.out.println(hashMap);
hashMap.remove("apple1"); // 존재하지 않는 키를 넣게 된다면 아무 일도 일어나지 않는다.
System.out.println(hashMap);
/*
출력 결과)
{banana=바나나, apple=사과1}
사과1
null
true
{banana=바나나}
{banana=바나나}
null
null
*/
2) LinkedHashMap 구현체
Map<String, String> linkedHashMap = new LinkedHashMap<>();
3) TreeMap 구현체
Map<String, String> treeMap = new TreeMap<>();
Random 클래스
예시
1) 로또 : 순서 X | 중복 X | 6자리 수(정수)
Set<Integer> lotto = new HashSet<Integer>();
Random random = new Random();
// lotto.add(random.nextInt(45) + 1);
// lotto.add(random.nextInt(45) + 1);
// lotto.add(random.nextInt(45) + 1);
// lotto.add(random.nextInt(45) + 1);
// lotto.add(random.nextInt(45) + 1);
while(lotto.size() < 6) {
lotto.add(random.nextInt(45) + 1);
}
System.out.println(lotto);
/*
출력 결과)
[35, 21, 11, 14, 30, 15]
*/
2) 연금복권 : 7자리. 첫번째 자리는 1~5까지, 나버지는 중복을 허용해서 0~9 | 순서O
List<Integer> youngeom = new ArrayList<Integer>();
for(int count = 0; count < 7; count++) {
if(count == 0) {
youngeom.add(random.nextInt(5) + 1);
continue;
}
youngeom.add(random.nextInt(10));
}
System.out.println(youngeom);
System.out.println();
/*
출력 결과)
[4, 2, 8, 8, 4, 2, 2]
*/
3) UUID
System.out.println(UUID.randomUUID().toString());
/*
출력 결과)
f3b74998-0437-4d6c-91e3-a7c2ef922e86
*/
날짜와 시간 처리에 대한 클래스
1) System.currentTimeMillis();
// int start = System.currentTimeMillis(); // Type mismatch: cannot convert from long to int
long start = System.currentTimeMillis();
System.out.println("시작 시간 : " + start);
// 경과 시간을
for(int index = 0; index < 10000000; index++) {
System.out.println("출력중...");
}
long end = System.currentTimeMillis();
System.out.println("종료 시간 : " + end);
System.out.println("경과 시간 : " + (end - start));
/*
출력 결과)
출력중...
출력중...
.
.
.
출력중...
출력중...
출력중...
종료 시간 : 1689756412368
경과 시간 : 9801
2) Date 클래스
Date date = new Date();
System.out.println(date);
// date = new Date("2023.07.01"); // java.lang.IllegalArgumentException
date = new Date(123,7,1,10,10,10); // 직관적이지 않는다. (현재년도 - 1900) 컴퓨터가 계산하기 쉽게 나오기 때문에. 지금과 같이생성자를 사용하는 방법은 쓰지 않는다.
System.out.println(date);
int year = 0;
int month = 0;
int dates = 0;
year = date.getYear();
month = date.getMonth();
dates = date.getDate();
System.out.println(year + " " + month + " " + dates); // 추가로 연산이 계속 필요함.
/*
출력 결과)
Wed Jul 19 17:49:31 KST 2023
Tue Aug 01 10:10:10 KST 2023
123 7 1
*/
3) Calendar 클래스
// Calendar calendar = new Calendar(); // Cannot instantiate the type Calendar
Calendar calendar = new GregorianCalendar();
System.out.println(calendar);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
dates = calendar.get(Calendar.DATE);
System.out.println(year + " " + month + " " + dates);
calendar.set(Calendar.YEAR, 2001);
year = calendar.get(Calendar.YEAR);
System.out.println(year);
/*
출력 결과)
java.util.GregorianCalendar[time=1689756760054,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Seoul",offset=32400000,dstSavings=0,useDaylight=false,transitions=30,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2023,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=4,DAY_OF_MONTH=19,DAY_OF_YEAR=200,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=5,HOUR_OF_DAY=17,MINUTE=52,SECOND=40,MILLISECOND=54,ZONE_OFFSET=32400000,DST_OFFSET=0]
2023 6 19
2001
*/
4) SimpleDateFormat 클래스
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // "-" 대신에 "."을 찍어도 상관없다.
System.out.println(simpleDateFormat.format(date));
System.out.println(simpleDateFormat.format(new Date())); // 현재시간
/*
출력 결과)
2023-08-01
2023-07-19
*/
정말 깊이 있는 글이었습니다.