본문 바로가기

자바

Day20


Set<E> 인터페이스르 구현하는 컬렉션 클래스들 
: 저장순서가 정해져 있지않고, 중복저장을 허용하지 않는다.

해시 알고리즘의 이해(데이터의 구분) -> 
데이터 -> 해시 알고리즘(데이터 분류, 그룹화) -> 알고리즘 적용 결과 
비교가 발라지고 성능이 좋아진다. 
HashSet<E> 클래스의 동등 비교 -> 
1단계 :hashCode 메소드의 반환 값을 해시 값으로 활용하여 검색의 그룹을 선택한다.(적절한 값을 선택하는 것이 성능 측면에 있어서 중요 하지만 너무 고민하면서 사용하진 말자!)
2단계 : 그룹내의 인스턴스를 대상으로 object 클래스의 equals 메소드의 반환값의 결과로 동등을 판단.
 값이 같은 객체가 이미 있다면(equals()가 true) 기존 객체를 덮어쓴다.
값이 같은 객체가 없다면(equals()가 false) 해당 entry를 LinkedList에 추가한다.

TreeSet<E> : 트리라는 자료구조를 기반으로 데이터를 저장한다.
데이터를 정련된 순서로(오름차순,내림차순) 저장하며, 데이터의 중보저장이 않된다. 정렬의 기준은 프로그래머가 직접 정의한다.
TreeSet<E> 인스턴스에 저장이 되려면 Comparable<T> 인터페이스
를 구현해야 한다.
• Comparable<T> 인터페이스의 유일한 메소드는 int compareTo(T 
obj); 이다.
• compareTo 메소드는 다음의 기준으로 구현을 해야한다. 
 인자로 전달된 obj가 작다면 양의 정수를 반환해라.(자리 바뀜) 
 인자로 전달된 obj가 크다면 음의 정수를 반환해라.(자리 x)
 인자로 전달된 obj와 같다면 0을 반환해라.
‘작다’, ‘크다’, ‘같다’의 기준은 프로그래머가 결정!

• Map<K, V> 인터페이스를 구현하는 컬렉션 클래스는 key-value 방식
의 데이터 저장을 한다.
• Value는 저장할 데이터를 의미하고, key는 value를 찾는 열쇠를 의미
한다. 
• Map<K, V>를 구현하는 대표적인 클래스로는 HashMap<K, V>와
TreeMap<K, V>가 있다.
• TreeMap<K, V>는 정렬된 형태로 데이터가 저장된다.


자바 자료구조 공부를 틈틈히 열심히 하자 
ArrayList, HashMap, Properties : 프로젝트에 이용 


trim ,calendar, System, nanomills,  -> api 검색 해보기 

 

자바 컬렉션 프레임워크 예제 10번 
package com.test_14;

import java.util.*;

public class FootballPlayer implements Comparable<FootballPlayer> {
	// 축구 선수의 이름, 번호, 팀, 나이
	private String name;
	private int number;
	private String team;
	private int age;

	// 생성자
	FootballPlayer(String name, int number, String team, int age) {
		this.name = name;
		this.number = number;
		this.team = team;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getTeam() {
		return team;
	}

	public void setTeam(String team) {
		this.team = team;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	// 저장된 선수들의 나이를 가지고 3개의 그룹을 만듬
	public int hashCode() {
		return age % 3;
	}

	// 팀과 이름 그리고 나이가 같으면 같은 선수라 판단.
	public boolean equals(Object obj) {
		boolean result = false;
		if (obj != null && obj instanceof FootballPlayer) {
			FootballPlayer fb = (FootballPlayer) obj;
			if (this.team.equals(fb.team) && this.name.equals(fb.name) && this.age == fb.age) {
				result = true;
			}
		}
		return result;
	}

	public String toString() {
		return "[" + name + ", " + number + ", " + team + ", " + age + "]";
	}
	
	@Override
	public int compareTo(FootballPlayer o) {
		//오름 차순 정렬
		int result = this.team.compareTo(o.getTeam()); //결과는  음수 / 양수 / 0
		//내림 차순 정렬 
//		int result = this.team.compareTo(o.getTeam()) * -1 ; 
//		int result = o.getTeam.compareTo(this.getTeam());

		//같은 팀 정렬
		if(result == 0) {
			result = this.name.compareTo(o.getName());
			// 같은 팀이고 이름이 같은 경우 정렬
			if(result == 0) {
				result = this.number - o.getNumber();
			}
		}
		return result;
//		// 팀 정렬
//		if (this.team.compareTo(o.team) > 0) {
//			result = 1;
//		} else if (this.team.compareTo(o.team) < 0) {
//			result = -1;
//		} else { // 같은 팀일 경우 이름 순으로 정렬
//			if (this.name.compareTo(o.name) > 0) {
//				result = 1;
//			} else if (this.name.compareTo(o.name) < 0) {
//				result = -1;
//			} else { // 같은 팀 같은 이름일 경우 번호로 정렬
//				if (this.number - o.number > 0) {
//					result = 1;
//				} else if (this.number - o.number < 0) {
//					result = -1;
//				}
//			}
//		}
//		return result;
	}
}
------------------------------------------------------------------------------------------
package com.test_14;

import java.util.*;

public class FootballPlayerList {

	public static void main(String[] args) {
		//1.축구선수 인스턴스를 저장할 수 있는 List<E> 컬렉션 인스턴스를 생성해서 인스턴스를 저장하고 출력하는 프로그램을 만들어봅시다. 
		
		List<FootballPlayer> list = new ArrayList<>();
		//데이터 저장
		list.add(new FootballPlayer("손흥민",7,"토트넘",30));
		list.add(new FootballPlayer("메시",5,"바르셀로나",31));
		list.add(new FootballPlayer("이영표",3,"토트넘",40));
		
		//데이터 처리
		Iterator itr = list.iterator();
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}	
	}
}
-------------------------------------------------------------------------------------------------------------------------------------------------
package com.test_14;

import java.util.*;

public class FootballPlayerHashSet {

	public static void main(String[] args) {
		//2. 축구선수의 인스턴스가 팀과 이름 그리고 나이가 같으면 같은 선수라 판단하고 입력이 되지 않도록 Set<E>컬렉션을 이용행서 축구선수 인스턴스를
		// 저장하고 출력하는 프로그램을 만들어 봅시다. 
		Set<FootballPlayer> set = new HashSet<>();
		set.add(new FootballPlayer("박지성",7,"맨유",31));
		set.add(new FootballPlayer("바지성",8,"맨유",32));
		set.add(new FootballPlayer("박자성",9,"맨시티",33));
		set.add(new FootballPlayer("박지상",7,"첼시",34));
		set.add(new FootballPlayer("박지성",7,"맨유",31));
		
		System.out.println("요소의 개수 : "+ set.size());
		
		Iterator itr = set.iterator();
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------
package com.test_14;

import java.util.*;

public class FootballPlayerTreeSet {

	public static void main(String[] args) {

		// 3. TreeSet<E>을 이용해서 팀 이름순으로 정렬하고, 같은 팀의 선수들은 이름 순으로 정렬하고,
		// 같은 이름의 선수는 번호 순으로 저장하는 프로그램을 만들어 봅시다.

		TreeSet<FootballPlayer> treeSet = new TreeSet<>();
		treeSet.add(new FootballPlayer("박지성", 7, "맨유", 33));
		treeSet.add(new FootballPlayer("루니", 10, "맨유", 34));
		treeSet.add(new FootballPlayer("에브라", 3, "맨유", 36));
		treeSet.add(new FootballPlayer("호날드", 18, "맨유", 32));
		treeSet.add(new FootballPlayer("반데사르", 1, "맨유", 40));
		treeSet.add(new FootballPlayer("드록바", 7, "첼시", 41));
		treeSet.add(new FootballPlayer("메시", 10, "바르셀로나", 30));
		treeSet.add(new FootballPlayer("수아레즈", 7, "바르셀로나", 33));
		treeSet.add(new FootballPlayer("루니", 6, "맨유", 29));
		treeSet.add(new FootballPlayer("조하트", 1, "맨시티", 28));
		treeSet.add(new FootballPlayer("덕배", 5, "맨시티", 32));
		treeSet.add(new FootballPlayer("에투", 8, "가나", 32));
		
		System.out.println("요소의 개수"+treeSet.size());
		Iterator itr = treeSet.iterator();
		while (itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}
----------------------------------------------------------------------------------------------------------------------
package com.test_14;

import java.util.*;

public class FootballPlayerMap {

	public static void main(String[] args) {
		Map<Integer, FootballPlayer> map = new HashMap<>();
		map.put(7, new FootballPlayer("박지성",7,"맨유",33));
		map.put(5, new FootballPlayer("드록바",5,"첼시",32));
		map.put(3, new FootballPlayer("박주영",3,"서울",34));
		map.put(2, new FootballPlayer("펠레",2,"브라질",35));
		map.put(1, new FootballPlayer("마라도나",1,"아르헨티나",37));
				
		Set<Integer> set = map.keySet();
		Iterator<Integer> itr = set.iterator();
//		Iterator itr = map.entrySet().iterator(); map에 저장된 모든 정보를 가져오는 entrySet() 메서드
		while(itr.hasNext()) {
        //key값의 목록을 출력
			System.out.println(map.get(itr.next()));
		}	
	}
}

 

 

자바 예외처리 예제 
숫자,영어 소문자/ 대문자를 제외한 입력이 들어왔을때 예외처리
char배열을 생성, 한글자씩 유니코드 조건으로 검사하는 코드 구성
package com.test_15;

import java.util.Scanner;

public class Chap10  {
	
	public static String getUserInput() {
		Scanner scan = new Scanner(System.in);
		String id = scan.nextLine();
		return id;
	}

	public static void main(String[] args) {
		System.out.print("사용자 아이디를 입력하세요. >>");
		try {
			String id = getUserInput();
			char[] t = id.toCharArray();
			for (int i = 0; i < t.length; i++) {
				//유니코드 
				// 숫자 : 48~57  					/소문자 65 ~ 90						//대문자 97~122	
				if ((48 > t[i] || t[i] > 57) && (65 > t[i] || t[i] > 90) && (97 > t[i] || t[i] > 122)) {
					throw new BadIdInputException("에러 발생");
				}	
				System.out.print(t[i]);
			}
			//오류 발생시 매개변수 참조를 통해 화면에 에러메세지 출력
		} catch (BadIdInputException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
}
----------------------------------------------------------------------------------------------------------------------
사용자 정의 예외 클래스 생성 
package com.test_15;

public class BadIdInputException extends Exception {
	public BadIdInputException(String msg) {
		super(msg);
	}
}

 

 

 

Calendar 인터페이스와 LocalDate 클래스를 이용한 출생 부터 현재까지의 날짜(days)를 계산 화면에 출력하는 예제 
LocalDate,LocalDateTime을  사용하려면 java 8 버전 이상일것!

 

package com.test_12;

import java.util.Calendar;

public class MyBrithTest {

	public static void main(String[] args) {
		// 자신의 생일을 기준으로 오늘까지 몇일을 살았는지 출력하는 프로그램을 만들어봅시다.
		// localDatetime -> 사용해보기
		// milli초는 1/1000 초
		Calendar cal = Calendar.getInstance();
		Calendar current = Calendar.getInstance();

		long days = 0;

		cal.set(1996, 02, 17);
		days = (current.getTimeInMillis() - cal.getTimeInMillis()) / (24 * 60 * 60 * 1000);
		System.out.println("살아온 날은 지금까지 :" + days + "일 입니다.");
	}
}
================================================================================================
package com.test_12;

import java.time.*;
import java.time.temporal.ChronoUnit;

public class Localdate {

	public static void main(String[] args) {

//		LocalDate cuurentTime = LocalDate.now();
		LocalDate cuurentTime = LocalDate.now();
		LocalDate myDate = LocalDate.of(1996, 02, 17);
		
		//ChronoUnit 클래스의 days.between 함수를 사용해서 내 생일부터 현재 날짜 까지의 차를 구한다.
		long days = ChronoUnit.DAYS.between(myDate, cuurentTime);
		System.out.println(days);
		
		Period period = cuurentTime.until(myDate);
//		System.out.println(period.getDays());
		
	}
}

'자바' 카테고리의 다른 글

day22  (0) 2021.06.13
day21  (0) 2021.06.13
Day19  (0) 2021.05.31
Day18  (0) 2021.05.28
Day 16  (0) 2021.05.26