-
학습목표
자료구조에 대한 개념자료구조란?
프로그램에서 사용할 많은 데이터를 메모리 상에서 관리하는 여러 구현방법들
효율적인 자료구조가 성능 좋은 알고리즘의 기반이 된다.
자료의 효율적인 관리는 프로그램의 수행속도와 밀접한 관련이 있다.
자바에서 제공되는 자료구조 구현 클래스
set 계열
순서없고 중복 못함(주머니에 순서없이 마구잡이로 집어넣은거랑 같음)
아이디, 주민번호, 사번등을 관리하는데 유용하다.
List 계열
객체를 순서에 따라 저장하고 관리하는데 필요한 메서드가 선언된 인터페이스
순서있고 중복 가능
자료구조 리스트 (배열, 연결리스트)의 구현을 위한 인터페이스
Map계열
쌍으로 이루어진 객체를 관리하는데 사용하는 메서드들이 선언된 인터페이스
key와 Value가 한쌍
HashMap은 가장 많이 사용되는 Map 클래스로 빠른 검색 속도를 제공한다.
ArrayList
선언하는 방법
ArrayList<Integer> list = new ArrayList<>(); ArrayList<Student> members = new ArrayList<>(); ArrayList<String> strings = new ArrayList<>();
값 추가 방법
//값 추가 방법 list.add(3); // 인덱스 0번이 할당 list.add(null); // 인덱스 1번 값은 null list.add(100); // 인덱스 2번 값은 100 list.add(1,20); // 인덱스 1번 값을 20으로 선언 (index번호 , 값 할당)
값 삭제하는 방법
list.remove(2); System.out.println(list.toString()); // [3, 20 ,100] 해당 하는 요소에 접근해서 제거하는것을 알 수 있다. System.out.println(list.size()); //3
매번 삭제하는 방법
//매번 삭제할려면 list.clear(); // <-- 전체 삭제 System.out.println(list.toString()); //[] System.out.println(list.size()); //0
값을 화면에 출력하는 방법
System.out.println(list.get(2)); //100 System.out.println(list.get(0)); //3 //System.out.println(list.get(20)); //없는데 접근하면 오류발생
for문 다른형식
for (int abc상관없음 : list) { System.out.println("변수명아무꺼나 됨 : " + abc상관없음); //3,20,100 }
리스트 배열 안에 값이 있는 크기만큼 돌며 값을 출력한다.
배열에 있는값 있는지 확인해보기
//값 검색 기능 사용해보기 // 리스트 안에 값이 있는지 없는지 확인하기 // 3, 20 ,100 <--- 70 값이 있는지 없는지 확인하는 코드 짜는법 // 70은 int 데이터 타입 자동으로 형변환 // 클래스 타입으로 Integer System.out.println(list.contains(70)); //false System.out.println(list.contains(100)); //true
배열안에 값이 있으면 true 없으면 false가 출력이 된다.
배열에 있는값이 몇번째 인덱스인지 확인해보는법
// 100 값이 몇 번째 인덱스 요소에 있나? // indexOf System.out.println(list.indexOf(100)); //2 //값이 있으면 해당하는 인덱스 번호를 리턴 한다. //만약 값이 없으면 무엇을 반환할까?? System.out.println(list.indexOf(5000)); //-1 //값이 없으면 반환한다.
indexOf를 쓰면 되며 값이 없으면 반환한다.
추가적인 내용
//추가 Iterator<Integer> iter = list.iterator(); //반복자 녀석으로 현 변환해 줌 terator() while(iter.hasNext()) { System.out.println("값 확인 방법 : " + iter.next()); }
순서가 없을때 위의 소스코드처럼 while문을 써서 쓸수있다.
Set
// set계열은 순서가 없고 중복이 불가하다. Set<Integer> set1 = new HashSet<>(); //다형성 set1.add(1); set1.add(10); set1.add(100); set1.add(500); set1.add(1); set1.add(1); System.out.println(set1.toString()); //[1, 100, 500, 10] System.out.println(set1.size()); //4
set은 똑같은 값이 중복이 안되며 (인덱스크기가 값이 같으면 늘어나지 않는다) 순서가 없다.
Set 삭제하는방법
//삭제 하는 방법 set1.remove(500); //없는 요소를 삭제 요청하더라도 오류 발생하지 않는다. set1.remove(1000); set1.clear(); //요소 전체 삭제 System.out.println(set1.toString()); //[]
연습문제
package ch05; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; public class SetMainTest3 { public static void main(String[] args) { HashSet<Integer> numberSet = new HashSet<>(); //무조건 6개 사이즈 가지는 numberSet 구성 하시오 ! //hint --> 반복문 사용 int count = 0; while(numberSet.size() !=6) { count++; numberSet.add(getRandomNumber()); } System.out.println(numberSet.toString()); System.out.println("반복 횟수 : " +count); } //end of main public static int getRandomNumber() { Random random = new Random(); //int value = random.nextInt(45) + 1; return random.nextInt(45) + 1 ; } } // end of class
출력값 [16, 17, 35, 19, 23, 40] 반복 횟수 : 6
while문을 써서 계속 반복 시켜 배열의 값이 겺쳐서 크기가 변하지 않더라도
크기가 6일때까지 돌리기 때문에 다른 숫자가 6개 출력이 되어서 나온다.map
package ch04; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Map.Entry; public class MapMainTest { public static void main(String[] args) { Map map; Map<String, String> map1 = new HashMap<>(); // value - null값 허용 Hashtable<String, String> map2 = new Hashtable<>(); // value - null값 허용 안 함 // C R U D map1.put("A01", "김포공항정문"); map1.put("A02", "김포공항후문"); map1.put("A03", "김포공항로비"); map1.put("B01", "인천공항정문"); map1.put("B02", "인천공항후문"); map1.put("B03", "인천공항로비"); map1.put("C01", null); // map 자료구조의 전체 값 확인하기 System.out.println(map1); // 값 꺼내는 방법 - key값을 통해서 값을 꺼낼 수 있다. System.out.println(map1.get("B03")); System.out.println(map1.get("C01")); System.out.println(map1.get("b01")); // 없는 key값을 요청하면 null이 반환된다. // 사이즈 확인 System.out.println(map1.size()); for (int i = 0; i < map1.size(); i++) { System.out.println(map1.get(i)); } // map 원래 순서가 없지만 잠깐 응용을 하면 key값으로 for문 정도는 활용할 수 있다. HashMap<Integer, String> map3 = new HashMap<>(); map3.put(0, "A"); map3.put(1, "B"); map3.put(2, "C"); map3.put(3, "D"); map3.put(4, "E"); for (int i = 0; i < map3.size(); i++) { System.out.println("value : " + map3.get(i)); } // 삭제하는 방법 map1.remove("C01"); // map1.clear(); System.out.println(map1.toString()); // 자료구조는 반복문과 if문을 많이 활용한다. // map 계열을 for문과 활용하는 방법 // map1<String, String> // Entry<String, String> entry1 = (Entry<String, String>)map1.entrySet(); // key, value 한번에 꺼낼 수 있다. - 반복하면서 for (Entry<String, String> entry2 : map1.entrySet()) { System.out.println("key : " + entry2.getKey()); System.out.println("value : " + entry2.getValue()); System.out.println("----------------"); } System.out.println("======================="); System.out.println(map1.keySet().size()); // map 값을 꺼낼 때 key값으로 접근 --> value // String str = map1.get("A01"); for (String key : map1.keySet()) { System.out.println("key : " + key); // 반복 돌면서 key값 확인 System.out.println("value : " + map1.get(key)); } } //end of main } //end of class
출력값 {A01=김포공항정문, A02=김포공항후문, B01=인천공항정문, A03=김포공항로비, B02=인천공항후문, B03=인천공항로비, C01=null} 인천공항로비 null null 7 null null null null null null null value : A value : B value : C value : D value : E {A01=김포공항정문, A02=김포공항후문, B01=인천공항정문, A03=김포공항로비, B02=인천공항후문, B03=인천공항로비} key : A01 value : 김포공항정문 ---------------- key : A02 value : 김포공항후문 ---------------- key : B01 value : 인천공항정문 ---------------- key : A03 value : 김포공항로비 ---------------- key : B02 value : 인천공항후문 ---------------- key : B03 value : 인천공항로비 ---------------- ======================= 6 key : A01 value : 김포공항정문 key : A02 value : 김포공항후문 key : B01 value : 인천공항정문 key : A03 value : 김포공항로비 key : B02 value : 인천공항후문 key : B03 value : 인천공항로비
{A01=김포공항정문, A02=김포공항후문, B01=인천공항정문, A03=김포공항로비, B02=인천공항후문, B03=인천공항로비, C01=null} - 전체 값 확인
인천공항로비 null null - key 값을 통해서 값을 꺼낼 수 있으며 값이 없는것은 null로 반환되는걸 알수있다.
7 null null null null null null null - 정확한 키값을 입력하지 않으면 null값이 뜨는걸 알수있다.
value : A value : B value : C value : D value : E - 키값을 입력해야 하는 map에서 숫자로 키값을 주어 for문을 돌려 값을 제대로 뜨는걸로 활용할수 있다.
그뒤로는 좀 더 응용하여 다른 for문으로 키값을 확실히 넣어 숫자가 아니더라도 map에서 값을 가져온걸 볼수있다.데이터를 저장할 때 : put()
객체를 다시 추출할때 : get()
키값이 있는지 확인할때 : containskey()
null값 체크 : isEmpty()
사이즈 : size()foreach문
for(데이터 타입 변수명 : 루프를 돌릴 객체){
// 반복할 코드
}
객체가 가지고 있는 인자의 수만큼 반복한다.'Java' 카테고리의 다른 글
자바의 I/O 스트림 (0) 2023.03.02 자료구조 연습문제 (0) 2023.02.21 쓰레드(Thread) (0) 2023.02.19 제네릭 (0) 2023.02.19 예외처리 (0) 2023.02.19