김기헌
List
•
저장된 요소들의 순서가 있고, 데이터에 중복 허용, 인덱스 번호에 의해 정렬(배열과 비슷한 동작)
•
List는 Collection Interface중 하나이다.
•
Array List와 LinkedList로 나눠진다.
•
크기 조절이 가능
•
초기 크기 지정 필요 x
//list 선언
List<자료형> 리스트 명 = new ArrayList(or LinkedList)<자료형(생략가능)>();
List.add(value); // List에 값 추가
List.add(index, value); //i ndex에 value값 추가, 중간 삽입의 경우 index이후에 값들은 한 칸씩 밀린다
List.remove(index)// index 위치에 있는 값 삭제
List.clear();// 모든 요소 삭제
List.get(index);// index위치에 있는 값 출력
List.size();// 리스트의 크기 반환
Java
복사
Set
•
집합의 의미로 순서가 없고, 중복 허용X
•
집합 연산 가능(합집합, 교집합, 차집합)
//Set 선언
Set<자료형> set명 = new HashSet(or TreeSet)<>();
Set.add(value); //value값 추가
Set.size(); // Set 사이즈 반환
Set.istEmpty(); // 비었는지 확인 비었으면True, 아니면 False 리턴
Set.contains(value); // value값이 있다면 True, 없으면 False 리턴
Java
복사
map
map + dependency
import java.util.*;
public class MapExercise {
public static void main(String[] args) {
MapStudentData mapStudentData = new MapStudentData();
HashMap<String,String> hMap= mapStudentData.getStudent();
PrintMap printMap = new PrintMap(hMap);
printMap.Print();
}
}
Java
복사
import java.util.HashMap;
public class MapStudentData {
private HashMap<String, String> students = new HashMap<String, String>();
public MapStudentData(){
DataInsert dataInsert = new DataInsert();
this.students = dataInsert.getStudent();
}
public HashMap<String, String> getStudent(){
return this.students;
}
}
Java
복사
import java.util.HashMap;
public class DataInsert {
private HashMap<String, String> students = new HashMap<String,String>();
public HashMap<String,String> getStudent(){
students.put("권하준", "https://github.com/dongyeon-0822/java-project-exercise");
students.put("조성윤", "https://github.com/kang-subin/Java");
students.put("안예은", "https://github.com/KoKwanwun/LikeLion.git");
students.put("남우빈", "https://github.com/lcomment/Algorithm_Solution--Java/tree/main/LikeLion");
return this.students;
}
}
Java
복사
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class PrintMap {
private Set<String> mapKeySet;
private HashMap<String,String> hMap;
private Iterator<String> it;
public PrintMap (HashMap<String,String> hMap){
this.hMap=hMap;
this.mapKeySet=hMap.keySet();
this.it = mapKeySet.iterator();
}
public void Print(){
while(it.hasNext()){
String key = it.next();
String value = hMap.get(key);
System.out.println("이름: "+key+" 깃 주소: "+value);
}
}
}
Java
복사
File
CodeUp 1021~1030
김상호
Set
Set은 List와 다르게 객체를 중복저장 할 수 없다. 또한 객체를 인덱스로 관리 하지 않기 때문에 저장 순서가 보장되지 않는다.
대표적인 클래스로 HashSet, TreeSet, LinkedHashSet 등이 있다.
HashSet
데이터를 중복 저장할 수 없고 순서를 보장하지 않는다.
•
Set<E>객체명 = new HashSet<E>();
TreeSet
LinkedHashSet
Map
Map은 리스트나 배열처럼 순차적으로 해당 요소 값을 구하지 않고 Key를 통해 value를 얻는다.
HashMap
HashMap은 Map을 구현한다. key와 value를 묶어 하나의 entry로 저장한다는 특징을 갖는다.
TreeMap
키와 값을 한 쌍으로 하는 데이터를 이진 검색 트리(binary search tree)의 형태로 저장한다.
이진 검색 트리는 데이터를 추가하거나 제거하는 등의 기본 동작 시간이 매우 빠르다.
LinkedHashMap
LinkedHashMap은 입력된 순서대로 데이터가 출력되는 특징을 가지고 있다.
임학준
List
•
객체를 인덱스로 관리한다
•
배열과의 차이점은 저장용량이 자동으로 증가하고 객체 저장시 자동 주소값이 부여된다
•
객체 제거시 해당 인덱스부터 마지막 인덱스까지 1씩 당겨진다(값 수정시 불리)
List<String> list = new ArrayList<String>();
List<String> list = new ArryList();
Java
복사
•
수업예제
import java.util.List;
//List를 생성하고 우리반 90명의 이름을 모두 넣는다
//List를 생성하고 우리반 90명의 이름,반,깃주소 세가지를 student에 담아서 List에 넣는다
public class ListExerciseMain {
public static void main(String[] args) {
ListExercise listExercise = new ListExercise();//객체 생성
List<String> students = listExercise.getStudents();
for(String student : students){ //student에 students를 하나씩 넣는다
System.out.println(student);
}
System.out.println(students.size());
}
}
Java
복사
import java.util.ArrayList;
import java.util.List;
public class ListExercise {
private List<String> students
public ListExercise() {//생성자 파라메터가 없으므로 바로실행
this.students = new ArrayList<>();//어짜피 생성자가 먼저 실행됨 초기화과정
this.students.add("김경록1");
this.students.add("김경록2");
this.students.add("김경록3");
this.students.add("김경록4");
this.students.add("김경록5");
//...90
}
public List<String> getStudents(){
return this.students;
}
}
Java
복사
Set
•
List컬렉션은 객체의 저장순서를 유지하지만 Set 컬렉션은 저장 순서가 유지되지 않는다
•
객체를 중복해서 저장할 수 없고, 하나의 null만 지정할 수 있다
Set<E> set = new HashSet<E>();
Java
복사
•
HashSet는 객체들을 순서 없이 저장하고 중복 저장하지 않는다
•
동일한 문자열은 동일한 객체로 간주한다
파일 출력
조국현
HashMap
Map 인터페이스를 구현한 대표적 Map 컬렉션
•
사용 방법
Map<K, V> map = new HashMap<K, V>();
Java
복사
K는 key, V는 value를 의미한다. 이 때 key 값으로는 기본 타입 사용 할 수 없고 클래스, 인터페이스 타입만 사용가능하다.
따라서 int 대신 Integer를 쓰는 것이다.
•
예시
Map<String, Integer> map = new HashMap<String, Integer>();
Java
복사
•
HashMap관련된 짤막 지식들
◦
학생이 많을 경우 맵이 리스트보다 빠르다.
◦
이름으로 찾을 때 더 빠르다.(키)
◦
해쉬 알고리즘으로 찾아서 해쉬맵이다.
◦
트리맵이 있는데, 이는 트리 알고리즘을 이용한다.
◦
해쉬맵과 트리맵이 각각 빠른 경우가 다르지만 대체로 해쉬가 빠르다.
HashMap 예제
•
HashMap에 데이터 넣는 예제
import java.util.HashMap;
public class MapExerciseMain {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("권하준", "https://github.com/dongyeon-0822/java-project-exercise");
map.put("조성윤", "https://github.com/kang-subin/Java");
map.put("안예은", "https://github.com/KoKwanwun/LikeLion.git");
map.put("남우빈", "https://github.com/lcomment/Algorithm_Solution--Java/tree/main/LikeLion");
map.put("최경민", "https://github.com/cmkxak/likelion-java-course");
System.out.println(map.get("황하준"));
}
}
Java
복사
map.put(key,value); 로 데이터를 넣는 예제이다.
예제 모음
•
NumberGenerator 인터페이스
public interface NumberGenerator {
int generate(int num);
}
Java
복사
인터페이스로 사용하는 NumberGenerator, 다른 클래스에 상속을 해주어서 다형성을 이용할 수 있다.
•
RandomNumberGenerator 클래스 (NumberGenerator 에 상속받음)
public class RandomNumberGenerator implements NumberGenerator{
@Override
public int generate(int num){
int result = (int) (Math.random()*num);
return result;
}
}
Java
복사
NumberGenerator에 상속을 받았고, 오버라이딩을 사용한다. 이 때 RandomNumberGenerator로 객체를 생성하여 generator(int num) 메소드를 호출하면 랜덤한 숫자를 리턴해준다.
(부모의 메소드를 호출하고 싶으면 super 키워드 사용.)
•
RandomAlphabetGenerator(NumberGenerator 에 상속받음)
public class RandomAlphabetGenerator implements NumberGenerator {
@Override
public int generate(int num) {
return (int)(Math.random()*num)+65;
}
}
Java
복사
이 클래스도 NumberGenerator에 상속받아 사용한다. generate 메소드에 매개변수로 26을 전달해주어서 알파벳에 해당하는 아스키코드를 랜덤생성 할 수 있다.
•
RndNumberWithoutDuplicate (Main 클래스)
import java.util.HashSet;
import java.util.Random;
public class RndNumberWithoutDuplicated {
public static void main(String[] args) {
RandomNumberGenerator randomNumberGenerator = new RandomNumberGenerator();
RandomAlphabetGenerator randomAlphabetGenerator= new RandomAlphabetGenerator();
HashSet<Integer> numbers = new HashSet<>();
HashSet<Character> alphabets = new HashSet<>();
char ch;
for (int i = 0; i < 50; i++){
int r = (randomNumberGenerator.generate(10));
int c = randomAlphabetGenerator.generate(26);
numbers.add(r);
ch = (char) c;
alphabets.add(ch);
}
System.out.println(numbers);
System.out.println(numbers.size());
System.out.println(alphabets);
System.out.println(alphabets.size());
}
}
Java
복사
HashSet을 이용하여 중복을 없앤다. 각각 객체를 생성하여 위에서 본 오버라이딩 된 메소드를 이용하여 데이터를 추가 한 뒤 출력해주었다.
•
알파벳체크 예제
public class AlphabetCnt {
static boolean isAlphabet(Character c){
if((c >= 'a' && c <= 'z') || (c>='A' && c<= 'Z')){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
String s1= "1122aabbccddeeffgghhiijkkkkkkkllm";
char ch;
for(int i = 0; i < s1.length(); i++){
ch = s1.charAt(i);
if(isAlphabet(ch))
{
ch = Character.toLowerCase(ch);
}
}
}
}
Java
복사
해당 예제는 String s1에 저장된 문자열을 한 글자씩 알파벳인지 아닌지 체크하는 예제이다.
•
위 예제를 HashMap을 이용해서 셈
public class MapExerciseMain_2 {
static boolean isAlphabet(Character c){
if((c >= 'a' && c <= 'z') || (c>='A' && c<= 'Z')){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
String repoAddr = "https://github.com/dongyeon-0822/java-project-exercise";
HashMap<Character, Integer> cntMap= new HashMap<>();
char ch;
String s;
for(int i = 0; i < 26; i++){
cntMap.put((char)(97+i),0);
}
for(int i = 0; i < repoAddr.length(); i++){
ch = repoAddr.charAt(i);
if(isAlphabet(ch))
cntMap.put(ch, cntMap.get(ch)+1);
}
for(int i = 0; i < 26; i++){
System.out.println(cntMap.get((char)(97+i)));
}
}
}
Java
복사
위 예제에서 더 나아가 해쉬맵에 key로 각 알파벳, value에는 해당 알파벳이 나타나는 횟수를 저장했다.
•
파일 읽기 예제( 한 바이트, 2바이트, n 바이트)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileExercise {
public void printFIles(){
File dir = new File("./");
File files[] = dir.listFiles();
for(File file : files) {
System.out.println(file);
}
}
public char readAChar(String fileName) throws IOException{
FileReader fileReader = new FileReader(fileName);
return (char)fileReader.read();
}
public String read2Chars(String filename) throws IOException{
FileReader fileReader = new FileReader(filename);
String str = "";
str += (char) fileReader.read();
str += (char) fileReader.read();
return str;
}
public String readNChars(String filename, int nByte) throws IOException{
FileReader fileReader = new FileReader(filename);
String str = "";
for(int i = 0; i < nByte; i++){
str += (char) fileReader.read();
}
return str;
}
public static void main(String[] args) throws IOException {
FileExercise fileExercise = new FileExercise();
char c = fileExercise.readAChar("a_file.txt");
String str = fileExercise.read2Chars("a_file.txt");
String str2 = fileExercise.readNChars("a_file.txt",5);
System.out.println(c);
System.out.println(str);
System.out.println(str2);
}
}
Java
복사
파일 읽기 예제인데, 구현된 Files와 FileReader 클래스를 이용하여 한결 편하게 가능하다. 이 때 FileReader에 구현된 read() 메소드는 호출할 때마다 파일에서 한 바이트씩 뒤로 가서 읽어준다.
최아영
Set
HashSet<키 타입, 값 타입> 변수명 = new HashSet<>();
•
순서가 없는 데이터의 집합이다.
•
데이터의 중복을 불허한다.
HashSet.add() | 주어진 객체를 추가 |
HashSet.remove() | 주어진 객체를 삭제 |
HashSet.clear() | 모든 아이템 삭제 |
HashSet.contains() | 주어진 객체를 존재 여부 |
HashSet.size() | 저장된 객체 수 반환 |
Map
HashMap<데이터 타입> 변수명 = new HashMap<>();
•
키와 값으로 구성된 객체를 저장하는 구조이다.
•
키는 중복이 불가능하지만 값은 중복이 가능하다.
•
기존에 저장된 키와 동일한 키로 값을 저장하면 기존의 값은 없어지고 새로운 값으로 대치된다.
HashMap.put(key, value) | 값 추가 |
HashMap.remove(key) | 키 값 제거 |
HashMap.clear() | 모든 값 제거 |
HashMap.get(key) | 키의 값 읽기 |
File 읽기
•
문자 파일을 읽을 수 있는 기능을 제공한다.
•
java.io.InputStreamReader 클래스를 상속받는다.
•
read() 메소드를 사용하여 한 글자 씩 읽어올 수 있다.
// 한 글자 읽기
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileOneLine {
public String ReadLine(String filename) throws IOException {
BufferedReader reader = new BufferedReader(
new FileReader(filename)
);
String str = reader.readLine();
reader.close();
return str;
}
public static void main(String[] args) throws IOException {
ReadFileOneLine readFileOneLine = new ReadFileOneLine();
String str = readFileOneLine.ReadLine("./testfile.txt");
System.out.println(str);
}
}
Java
복사
•
버퍼를 사용한다.
•
FileReader보다 좀 더 효율적이다.
•
readLine() 메소드를 사용하여 한 줄 씩 읽어올 수 있다.
// 한 줄 읽기
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileOneLine {
public String ReadLine(String filename) throws IOException {
BufferedReader reader = new BufferedReader(
new FileReader(filename)
);
String str = reader.readLine();
reader.close();
return str;
}
public static void main(String[] args) throws IOException {
ReadFileOneLine readFileOneLine = new ReadFileOneLine();
String str = readFileOneLine.ReadLine("./src/_1006/file/testfile.txt");
System.out.println(str);
}
}
Java
복사