무엇이든 담을 수 있는 상자를 만들어보자!
< 최상위 클래스인 Object를 이용한 무엇이든 담을 수 있는 ObjectBox >
public class ObjectBox {
private Object object;
public void set(Object obj){
this.object = obj;
}
public Object get() {
return this.object;
}
}
< 위 상자를 이용한 Main>
public class ObjectBoxMain {
public static void main(String[] args) {
ObjectBox box = new ObjectBox();
box.set("kim");
🚩String str = (String)box.get();//형변환 해줘야 한다.
System.out.println("str.toUppertCase() = " + str.toUpperCase());
}
}
→ get()메서드로 객체를 얻을 때 Object로 얻기 때문에 형변환 해줘야한다.
ObjectBox는 어떤 Object든 저장할 수 있고, 어떤 Object를 꺼낼 수도 있다.
하지만, 꺼내서 사용할 때는 원래 타입으로 변환시키는 번거로운 과정이 필요하다.
GenericBox
🏁 GenericBox
제네릭의 장점
< GenericBox Class >
public class GenericBox <T>{
private T t;
public void set(T obj){
this.t=obj;
}
public T get() {
return this.t;
}
}
< GenericBox Main >
public class GenericBoxMain {
public static void main(String[] args) {
GenericBox<String> genericBox = new GenericBox<>();
genericBox.set("kim");
String str = genericBox.get();
System.out.println("str.toUpperCase() = " + str.toUpperCase());
}
}
컬렉션 프레임워크 (Collection Framework)
컬렉션 프레임워크란?

🏁 java.util.Collection 인터페이스 (=바구니같은 역할)
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("kim");//ArrayList가 오버라이딩 한 add 메서드 이용
collection.add("lee");
collection.add("hong");
System.out.println(collection.size());//ArrayList가 오버라이딩 한 size함수 이용
Iterator<String> iter = collection.iterator();
while(iter.hasNext()){// 출력값이 kim,lee,hong 순서대로인 이유
String str = iter.next(); // -> ArrayList가 Collection의 메서드를 오버라이딩 하고 있어서
System.out.println(str);
}
}
-> 🚩언제든 인터페이스를 구현한 더 좋은 클래스들이 있을 수 있기 때문에 위에서 Collection 타입으로 코드를 작성한 것처럼 인터페이스 타입으로 코드를 작성해야한다.
🏁java.util.List 인터페이스 (=바구니에 들어온 순서를 기억하는 자료구조)
public static void main(String[] args) {
// 자료구조객체들은 제네릭을 사용하지 않으면
// Object 타입을 저장합니다.
ArrayList list = new ArrayList();
list.add("kim");
list.add("lee");
list.add("hong");
String str1 = (String)list.get(0);
String str2 = (String)list.get(1);
String str3 = (String)list.get(2);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
🏁java.util.Set 인터페이스(=바구니에 들어온 데이터의 중복을 허용하지 않는 자료구조)
public static void main(String[] args) {
Set<MyData> mySet = new HashSet<>();
mySet.add(new MyData("kim", 500));
mySet.add(new MyData("lee", 200));
mySet.add(new MyData("hong", 700));
mySet.add(new MyData("hong", 700));//위에 것과 반복 같은데 왜 둘 다 저장되지?
// -> 서로 다른 객체이기 때문이다.
Iterator<MyData> iter = mySet.iterator();
while(iter.hasNext()){
MyData myData = iter.next();
System.out.println("myData = " + myData);
}
}
< MyData Class >
class MyData{
private String name;
private int value;
public MyData(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return "MyData{" +
"name='" + name + '\'' +
", value=" + value +
'}';
}
}
🏁java.util.Iterator 인터페이스 (=바구니의 것을 꺼내는 역할)
🏁java.util.Map 인터페이스 (=키와 값을 가진 자료구조)
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k1", "hello");
map.put("k2", "hi");
map.put("k3", "안녕");
map.put("k3", "안녕하세요");//기존의 키값에 덮어쓴다.
Set<String> keySet = map.keySet();//Map에 있는 모든 키들에 접근할 수 있는 Set 객체가 나옴
Iterator<String> iter = keySet.iterator();//set으로부터 하나씩 꺼낼 수 있는 iterator 반환
while(iter.hasNext()){
String key = iter.next();
String value = map.get(key);
System.out.println((key + " : " + value));
}
}
collections 클래스
sort(list) : 정렬하는 메서드
shuffle(list) : 섞는 메서드