01. Java (v)
02. git
03. Database
04. Jsp [Server]
05. 미니프로젝트 (3W)
06. HTML,CSS
07. JS
08. SpringFramework , SrpingBoot
09. React JS [Front-end]
10. 중간프로젝트 (1M)
11. Linux 명령어
12. AWS 클라우드
13. DevOps - Docker
14. App - Android
15. 최종프로젝트 (1M)
데이터를 중복 없이 저장하는 자료구조
리스트와 반대인 특징
해시 알고리즘을 사용해서 저장 순서를 알 수 없음.
저장 순서가 없기 때문에, 데이터를 조회하는 메서드가 없음
값의 확인은 반복자를 사용해서 확인
HashSet
Set<String> set = new HashSet<>();
// 값의 추가
set.add("java");
set.add("database");
set.add("git");
set.add("css");
set.add("java");
set.add("java");
System.out.println("셋 크기: "+set.size());
System.out.println(set.toString());
// 값 조회 - get메서드가 없고, 반복자를 통해서 하나씩 꺼내봐야 함.
// 반복자로 변경
Iterator<String> iter = set.iterator();
// 다음이 있는지 확인하고 반복
while(iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("-".repeat(30));
for(String s:set) {
System.out.println(s);
}
// 값의 검색
if(set.contains("git")) {
System.out.println("git이 포함되어 있습니다.");
}
// 값의 삭제
// set에서는 값을 매개변수로 넣어서 삭제
set.remove("java");
System.out.println(set.toString());
TreeSet
// 중복 x , 자동으로 오름차순 정렬
Set<String> set = new TreeSet<>();
set.add("강아지");
set.add("강아지");
set.add("송아지");
set.add("망아지");
set.add("얼룩송아지");
System.out.println(set.toString());
// 나머지 사용 방법은 HashSet과 동일
HashMap
메서드
// <키에 대한 타입, 값에 대한 타입>
Map<Integer,String> map = new HashMap<>();
// 맵에 값을 추가
map.put(1, "홍길동");
map.put(2, "이순신");
map.put(3, "홍길자");
map.put(4, "홍길동");
System.out.println("맵의 크기 :"+map.size());
System.out.println(map.toString());
// 맵은 같은 key를 저장했을 경우, key에 대한 value를 수정
map.put(4, "신사임당");
System.out.println(map.toString());
// 값을 얻기 - 키를 주면 값을 반환
String value= map.get(3);
System.out.println("3번에 대한 값은: "+value);
// 맵은 순서가 있지는 않기 때문에, 반복을 돌리려면 반복자를 활용
// keySet -> key를 set으로 반환
Set<Integer> keySet = map.keySet();
for(Integer key :keySet) {
System.out.println("키:"+key + ", 값:"+map.get(key));
}
System.out.println("-".repeat(30));
// EntrySet -> key와 value를 통쨰로 꺼내줌
Set<Entry<Integer, String>> entrySet= map.entrySet();
// 엔트리 안에는 key, value를 얻는 함수 getKey(),getValue()가 있음
for(Entry<Integer,String> e:entrySet) {
System.out.println("키:"+e.getKey()+", 값:"+e.getValue());
}
// map에 있는 key의 유무 확인
if(map.containsKey(1)) {
System.out.println("1번 키는 이미 존재 함");
}
//map의 삭제
map.remove(1);
System.out.println(map.toString());
TreeMap
클래스
주요 메서드
/*
*
* io패키지의 모든 클래스는 생성자가 throws키워드를 던지고 있어서
* 모두 try~catch블록과 함께 사용해야 함
*
*
*/
String path = "C:\\Users\\Windows\\Desktop\\hello.txt";
FileOutputStream fos=null;
try {
fos=new FileOutputStream(path);
String str = "길동이";
fos.write(str.getBytes());
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String path = "C:\\Users\\Windows\\Desktop\\hello.txt";
InputStream fis = null;
try{
fis=new FileInputStream(path);
// 한글자씩 읽기
//while(true) {
// int data =fis.read(); // 읽은 데이터 한글자 반환
// if(data==-1) break;
// System.out.print((char)data);
//}
// 바이트 배열로 읽기
byte[] arr = new byte[100];
int result = fis.read(arr); // 읽은 데이터의 길이를 반환
System.out.println("읽어들인 데이터길이:"+result);
System.out.println(Arrays.toString(arr));
}catch(IOException e) {
e.printStackTrace();
}finally {
try{
fis.close();
}catch(IOException e2) {
}
}
InputStream fis = null;
OutputStream fos = null;
String inputPath="C:\\Users\\Windows\\Desktop\\file\\copy.png"; // 읽어들일 파일명
String outputPath="C:\\Users\\Windows\\Desktop\\file\\filecopy\\hello.png"; // 저장할 파일명
try {
fis = new FileInputStream(inputPath);
fos = new FileOutputStream(outputPath);
//100바이트 단위로 읽은
byte[] arr = new byte[100];
int result;
// 읽은 길이 반환, 더이상 읽을 데이터가 없으면 -1 반환
while((result=fis.read(arr))!=-1) {
System.out.println(Arrays.toString(arr));
fos.write(arr, 0, result); // 데이터, 시작위치, 쓸위치
}
System.out.println("파일 복사 성공");
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
fos.close();
}catch(IOException e2){
}
}
/*
* 문자를 써서 파일을 저장할 때 사용하는 클래스는 FileWriter
* 2바이트 기반으로 동작하기 때문에, 한글처리가 가능
*
*/
Writer fw = null;
String path="C:\\Users\\Windows\\Desktop\\file\\bye.txt";
try {
fw = new FileWriter(path);
String str ="지금은 4시 12분 입니다.\n11";
fw.write(str);
System.out.println("파일 출력 완료");
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
fw.close();
}catch(IOException e2) {
}
}
2바이트 기반으로 문자를 읽어들일 때 사용하는 클래스
String path="C:\\Users\\Windows\\Desktop\\file\\bye.txt";
Reader rd = null;
try {
rd = new FileReader(path);
int result;
while((result=rd.read())!=-1) { // 한글자를 읽어들임, 더이상 읽을 값이 없으면 -1
System.out.print((char)result);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
rd.close();
}catch(IOException e2) {
}
}