본문 바로가기

말하는 감자 탈출하기

Java day8

Object 클래스는 모든 클래스의 최상위 클래스임

모든 클래스는 Object 클래스를 상속받아 그 함수를 사용하고 재정의할 수 있음(*final 키워드가 있는 메서드는 예외)

 

별개의 인스턴스를 같다고 하려면 논리적인 같음을 재정의하면 되는데 equals와 hashCode를 재정의해줌

hashCode를 재정의할 때는 equals에 사용된 같다의 조건의 멤버변수를 활용함

 

스트링이 늘어나는 게 아니라 메모리 낭비가 심하다

프로토콜을 연결할 때 concat 메서드를 사용할 수 있는데 

stringbuilder/ stringbuffer클래스는 가변적 배열을 가지고 있기때문에 메모리 오버헤드 없이 concat 가능함

stringbuffer는 멀티스레드 프로그래밍에서 동기화를 보장하고 싱글 스레드인 경우엔 stringbuilder가 권장됨

 

StringBuilder buffer = new StringBuilder();

buffer.append(값)

buffer 변수에 값을 추가한 후 스트링으로 변환

String all = buffer.toString();

 


12. 컬렉션 프레임워크 활용하기

 제너릭 프레임워크 <>

 

package generic;

import java.util.ArrayList;

public class GenericTest {

	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<String>();
// 		<String> 이 부분이 제너릭 -> 제너릭을 쓰면 다운캐스팅이 불필요함
//		ArrayList list = new ArrayList(); // 제너릭을 쓰지 않은 경우
		list.add("test");
		
		list.get(0);// Object를 넣어줬으므로 list는 Object임
//		Object obj = 가 우측에 생략되어있다고 보면 됨
// 		스트링으로 받고싶으면 아래처럼 다운캐스팅을 해줘야 함 		
//		String obj = (String)list.get(0); 

	}

}

제너릭 클래스

public class Genericprinter<T>{
	private T material;
	
	public void setMaterial(T material) {
		this.material=material;
	}
	
	public T getMaterial() {
		return material;
	}
}

-> T는 자료형 매개변수(Type)

여러 참조 자료형으로 대체될 수 있느 부분을 하나의 문자로 표현

 

package generic;

public class Plastic {
	
	public String toString() {
		return "재료는 plastic 입니다";
	}

}
//-----------------------------------------
package generic;

public class Powder {
	
	public String toString() {
		return "재료는 powder 입니다";
	}

}
//----------------------------------------
package generic;

public class GenericPrinter<T> {
	
	private T material;
	
	public void setMaterial(T material) {
		this.material=material;
	}
	
	public T getMaterial() {
		return material;
	}
	
//	public String toString() {
//		return material.toString();
//	}// 재정의해서 각 클래스의 toString이 출력될 수 있도록 함
	
	public String toString() {
		return "재료 공통으로 출력되는 문자열";
	}
}
//----------------------------------------
package generic;

public class GenericPrinterTest {

	public static void main(String[] args) {
		
		GenericPrinter<Powder> powderPrinter = new GenericPrinter<Powder>();
		powderPrinter.setMaterial(new Powder());
		System.out.println(powderPrinter);
		
		GenericPrinter<Plastic> plasticPrinter = new GenericPrinter<Plastic>();
		plasticPrinter.setMaterial(new Plastic());
		System.out.println(plasticPrinter);
		
		// toString을 GenericPrinter에서 따로 정의하지 않은 경우 주솟값 출력
		//		generic.GenericPrinter@7852e922
		//		generic.GenericPrinter@4e25154f
	}

}

지금은 T 캐릭터에 어떤 것이든 다 넣을 수 있음 

ex. water를 만들어서 넣으면 water도 그냥 들어감

그래서 T캐릭터에 넣을 수 있는 걸 한정하기 위해서 T를 Material을 상속받게 함

그러면 Material을 상속받은 클래스만 T 캐릭터를 사용할 수 있음

 

Material 클래스를 추상클래스로 만들어서 추상메서드를 만들고

상속받는 클래스들이 해당 메서드를 제너레이트하도록하고

객체에서 멤버변수를 통해서 material.메서드를 실행하게 되면 코드 한줄에 여러 개의 기능을 실행할 수 있게됨 ->이걸 뭐라하더라???

--> 공통된 여러개의 기능을 구현할 수 있음

 

컬렉션 프레임워크 

프로그램 구현에 필요한 자료구조를 구현한 라이브러리

 

- 컬렉션 인터페이스: 하나의 데이터를 핸들링함

java.util패키지에 구현되어있음

list -ArrayList, Vector(멀티 스레드에서 동기화 기능 有), LinkedList

set-HashSet,TreeSet

 

- 맵 인터페이스: 쌍으로 된 데이터를 핸들링함. 키-밸류 쌍으로 이뤄져 있음

Hashtable, HashMap, TreeMap

 

HashSet

package collection;

public class Student {
	
	String studentName;
	int studentId;
	
	public Student(String studentName, int studentId) {
		this.studentId=studentId;
		this.studentName=studentName;
	}
	
	public String toString() {
		return studentName + "," + studentId;
	}
}

//-------------------------------------------------------------

package collection;

import java.util.HashSet;

public class HashSetTest {

	public static void main(String[] args) {

		HashSet<Student> set = new HashSet<Student>(); // 중복을 허용하지 않음
		
		set.add(new Student("Kim",1001));
		set.add(new Student("Park",1002));
		set.add(new Student("Park",1002));
		
		System.out.println(set); // [Kim,1001, Park,1002, Park,1002]
		// 주솟값이 다르기때문에 두개의 Park를 같은 인스턴스로 인식하지 않아 중복을 허용하는 것처럼 보임
		// equals와 hashCode를 재정의해주면 같은 논리적으로 같은 값이 되므로 Park인스턴스는 한번만 나옴
		// hashSet의 add는 equals와 hashCode를 체크하기때문에 꼭 재정의를 해야 우리가 생각하는 '중복'을 허용하지 않는 특성을 유지할 수 있음


	}

}

Tree 자료구조 - 정렬되어있음

정렬 기준은 클래스에 정의함

 

 ex. String은 이미 내부에 정렬기준이 있으므로 그에 따라서 정렬함

import java.util.TreeSet;

//main에 구현된 코드
TreeSet<String> strSet=new TreeSet<String>();
		strSet.add("test");
		strSet.add("tes2t");
		strSet.add("2test");
        
System.out.println(strSet); // [2test, tes2t, test]

jdk 내부적으로 트리는 레드-블랙트리(이진탐색트리)를 사용함

 

Student 클래스로 똑같이 실행시키면

package collection;

import java.util.TreeSet;

public class HashSetTest {

	public static void main(String[] args) {

		TreeSet<Student> set = new TreeSet<Student>(); 
		
		set.add(new Student("Kim",1001));
		set.add(new Student("Park",1002));
		set.add(new Student("Park",1002));
		
		System.out.println(set); 
	}

}

이 상태에서 실행시키면 

이런 오류가 남

Comparable을 구현하지 않아서 생긴 오류이므로 Student 클래스로 가서 구현해준다

package collection;

// 추가된 부분
public class Student implements Comparable<Student> {
	
	String studentName; 
	int studentId;
	
	public Student(String studentName, int studentId) {
		this.studentId=studentId;
		this.studentName=studentName;
	}
	
	public String toString() {
		return studentName + "," + studentId;
	}
	
//  정렬기준을 학번으로 함
	@Override
	public int compareTo(Student std) {
		return this.studentId-std.studentId;// 양수가 되면 오름차순 정렬
	}
}

출력결과 오름차순으로 출력됨 [Park,1007, Kim,1008, Park,10027]

음수가 되면 내림차순

 

string으로 비교해서 오름차순 정렬하고 싶다면

this.name.CompaeTo(비교대상) ->-1곱하면 내림차순 정렬됨

 

hashMap

package collection;

import java.util.HashMap; // 해시 테이블을 개선함
import java.util.TreeMap;

public class HashMapTest {

	public static void main(String[] args) {
		
		HashMap <Integer, String> map = new HashMap<Integer, String>();
		
		map.put(100,"진자잠옴");
		map.put(500,"죽을뻔했다");
		map.put(300,"ㅋㅅㅋ");
		
		String str = map.get(100); // 키 값을 이용한 검색
		System.out.println(str); // 진자잠옴
		 
		System.out.println(map); // {100=진자잠옴, 500=죽을뻔했다, 300=ㅋㅅㅋ}
		
		TreeMap<Integer, String> treemap=new TreeMap<Integer, String>();
		// 키 기반으로 정렬함
		treemap.put(100,"트리");
		treemap.put(200,"트리뻔했다");
		treemap.put(300,"ㅌ리ㅋ");
		
		System.out.println(treemap); // {100=트리, 200=트리뻔했다, 300=ㅌ리ㅋ}
	}

}

 

예제 전혀 이해가 안됨

package practice;

public class Car {
	
	String name;
	
	public Car() {}
	public Car(String name) {
		
		this.name=name;
	}

}
package practice;

import java.util.HashMap;

public class CarFactory {
	
	private static CarFactory instance = new CarFactory();
	HashMap<String, Car> carMap = new HashMap<>();
	
	private CarFactory(){}
	public static CarFactory getInstance() {
		
		if(instance ==null) {
			
		}
			instance = new CarFactory();
		return instance;
		
	}
	public Car createCar(String name) {
		
		if(carMap.containsKey(name)) {
			return carMap.get(name);
		}
		
		Car car = new Car();
		carMap.put(name, car);
		return car;
		
	}

}
package practice;

public class CarTest {

	public static void main(String[] args) {
		CarFactory factory = CarFactory.getInstance();
		
		Car car1=factory.createCar("내차");
		Car car2=factory.createCar("내차");
		Car car3=factory.createCar("남차");
		System.out.println(car1==car2); //true
		System.out.println(car3==car2); //false

	}

}

 

 

'말하는 감자 탈출하기' 카테고리의 다른 글

화면 설계도 작성하기  (0) 2023.05.15
Java day9  (0) 2023.05.14
Java day7  (1) 2023.05.12
java를 해야하는데 ㅎㅅㅎ  (0) 2023.05.07
감자의 에러  (0) 2023.05.04