자바 프로그래밍 18일차 수업

김형우·2022년 11월 16일
0

Java

목록 보기
17/22

1. 콜렉션 프레임워크란?

콜렉션 프레임워크란 자료구조 및 알고리즘을 구현해 놓은 일종의 라이브러리이다.
제네릭 기반으로 구성되어있다.

2. ArrayList 와 LinkedList 의 장단점은?

ArrayList : 주소값이 연속적으로 할당되어 있어서 검색(참조)할때
속도면에서 더 빠르다.

LinkedList : ArrayList는 연속적으로 되어있어 삭제/삽입때마다 완전히 삭제한 뒤 새로 생성하는 반면, LinkedList는 자료의 주소값을 전혀 떨어져있는 다음 인스턴스에 주면서 넘기면서 이어지기 때문에 다음에 넘겨줄 부분만 수정하면 되기에 삭제/삽입에 더욱 용이하다

3. Scanner 클래스로 -1이 입력될 때까지 양의 정수를 입력 받아 저장(List)하고 검색하여 가장 큰 수를 출력하는 프로그램을 작성하라.

소스코드


public static void main(String[] args) {

		System.out.println("담을 수를 입력해주세요, -1를 입력시 종료됩니다.");
		Scanner sc = new Scanner(System.in);
		int inserted_num = sc.nextInt();

		ArrayList<Integer> arr1 = new ArrayList<>();

		while (true) {
			if (inserted_num == -1) {
				System.out.println("종료되었습니다.");
				break;
			} else if (inserted_num > 0) {
				arr1.add(inserted_num);
				inserted_num = sc.nextInt();
			} else
				inserted_num = sc.nextInt();

		}
		int max = 0;
		for (int i = 0; i < arr1.size(); i++) {
			if(arr1.get(i) > max) {
				max = arr1.get(i);
			}
		}
                System.out.println("담겨져있는 숫자들“);
		for (Integer num : arr1) {
			System.out.print(num + " ");
		}
		System.out.println(”가장 큰 수“);
		System.out.println(max);

4. 로또 프로그램을 작성하시오.(Set 으로)

import java.util.HashSet;
import java.util.Set;
// ctrl+shift+o로 자동 import
	
public class SetLotto {

	public static void main(String[] args) {

		Set<Integer> Lotto = new HashSet<>();
		//Set으로 정수형 래퍼클래스를 담은 Lotto객체 생성	
			
		while(Lotto.size() != 6) {
			Lotto.add((int) (Math.random() * 46+1));
            
            // Lotto의 길이가 6이 될때까지(중복없이) add함수 반복
		}
		
		for(Integer i : Lotto)
			System.out.print(i + " ");
	}

}

5. Set에 대하여 설명하시오.

Set의 특성은, 데이터의 중복이 없게하며 저장 순서가 유지되지 않는것이다.

6. 출력이 아래와 같이 나오도록 하시오(필수) ⭐️

    HashSet<Num> set = new HashSet<>();
    set.add(new Num(7799));
    set.add(new Num(9955));
    set.add(new Num(7799));

    System.out.println("인스턴스 수: " + set.size());

    for(Num n : set)
        System.out.print(n.toString() + '\t');

    System.out.println();

출력

인스턴스 수: 2
7799	9955

소스코드


class Num{

	private int num;
	public Num(int n){
    	num = n;
    }
	@Override
	public String toString(){
    	return String.valueOf(num);
    }
    @Override
    public int hashCode(){
    	return num % 2;
    }
    @Override 
    public boolean equals(Object obj) {
    	if(num == ((Num)obj).num)
        	return true;
        else
        	return false;
    }
	/* 강사님 방식
    
    public boolean equals(Object obj) {
		if(obj instanceof Num) {
			Num n1 = (Num)obj;
			if(this.name.equals(n1.name))
				return true;
		}
		
		return false;
	}
    */
}

7. Set 호출되는 원리와 순서를 설명하시오.

1단계 : hashCode()에 정의되어있는 메소드의 반환값에 기반하여 부류를 결정한다.

2단계 : 선택된 부류 내에서 eqauls() 메소드를 호출해서 동등한지 비교한다.

8.아래와 같이 출력되도록 하시오.

HashSet<Person> hSet = new HashSet<Person>();
hSet.add(new Person("LEE", 10));
hSet.add(new Person("LEE", 10));
hSet.add(new Person("PARK", 35));
hSet.add(new Person("PARK", 35));

System.onut.println("저장된 데이터 수: " + hSet.size());
System.out.println(hSet);

출력결과

저장된 데이터 수: 2
[LEE(10세), PARK(35세)]

소스코드


class Person {
	String name;
    int age;
    
    Person(String name, int age){
    	this.name = name;
        this.age = age;
    }
    
    public String toString() {
    	return name + "(" + age + "세)";
    }
    
    public int hashCode() {
    	return (name.hashCode() + age) / 2;
    }
    @Override
    public boolean equals(Object obj) {
    	if (!(obj instanceof Person)) {
    		return false;
    	}
        return (age == ((Person)obj).age && name.equals(((Person)obj).name));
    }

}
profile
개발자 지망생

0개의 댓글