목차

  1. Collection Framework
  2. Collection Framework의 핵심 인터페이스 - List, Set, Map
  3. Collection Frmawork의 동기화(synchronization)

1. Collection Framework

  • Collection
    - 다수의 데이터, 즉, 데이터 그룹을 의미한다.

  • Framework
    - 표준화, 정형화된 체계적인 프로그래밍 방식
  • Collection framework
    - 데이터 군(群)을 저장하는 클래스들을 표준화한 설계
    - 다수의 데이터를 쉽게 처리할 수 있는 방법을 제공하는 클래스들로 구성
    - JDK1.2부터 제공
  • Collection class
    - 다수의 데이터를 저장할 수 있는 클래스(예, Vector, ArrayList, HashSet)
  • Collection method
    - int size();
    - boolean isEmpty();
    - boolean add(Object element);
    - boolean remove(Object obj);
    - boolean removeAll(Collection other);
    - boolean contains(Object obj);
    - Iterator iterator(); // iterator 인터페이스를 얻어냄
    - Object[] toArray(); // 컬렉션에 들어있는 요소를 배열 객체로 바꿈 

 

 

2. Collection Framework의 핵심 인터페이스

List interface

순서가 있는 데이터 집합. 데이터 중복 허용

구현 클래스: ArrayList, LinkedList, Stack, Vector ...

 

Set interface

순서를 유지하지 않는 데이터 집합. 데이터 중복 허용x

구현 클래스: HashSet, TreeSet, ...

 

Map interface

키(key)와 값(value)의 쌍으로 이루어진 데이터 집합. 순서유지되지 않으며, 키 중복 허용되지 않음. 값 중복 허용

구현 클래스: HashMap, TreeMap, HashTable, Properties ...

 

1) List Interface

- Sequence(연속된 상태) 라고도 함.

- 순서 보장, 중복 허용

- 구현 클래스: Stack, Vector, ArrayList ...

- 배열과의 차이점: 배열은 크기가 고정, List 구조는 가변적 길이

 

 

Method

Element get(int index)  // element 가져오기

void set(int index, Element e);  // element 교체

boolean contains(Element e)

int indexOf(Element e)

int lastIndexOf(Element e)

...

 

Iterator pattern

// 기본 list의 element 값 가져오기
for (int i = 0; i < list.size(); i++) {
	System.out.print(list.get(i) + "\t");
}

// interator 객체로 element 얻어오기 => Iterator Pattern
Iterator elements = list.iterator();	
while (elements.hasNext()) {
	System.out.print(elements.next() + "\t");
}

// LinkedList에 있는 메소드 사용하여 element가져오기
int i = 0;
while (!linkedList.isEmpty()) {
	System.out.println(i + "->" + linkedList.poll());	// 메모리에서 삭제하면서 element를 가져옴.
	i++;
}

 

ArrayList와 LinkedList 비교

컬렉션 읽기(접근시간) 추가 / 삭제  
ArrayList 빠르다 느리다 순차적인 추가삭제는 빠름.
비효율적인 메모리 사용
LinkedList 느리다 빠르다 데이터가 많을수록 접근성이 떨어짐.

 

...더보기

ArrayList와 LinkedList 성능 비교 코드

// 입력 성능이 필요한 곳에서는 Linkedlist를 사용하는 것이 성능면에서 좋다.
List<String> list1 = new ArrayList<String>();
List<String> list2 = new LinkedList<String>();

long startTime;
long endTime;

startTime = System.nanoTime();

for (int i = 0; i < 10000; i++) {
	list1.add(0, String.valueOf(i));
}

endTime = System.nanoTime();
System.out.println("ArrayList 걸린 시간: " + (endTime - startTime) + "ns");

startTime = System.nanoTime();

for (int i = 0; i < 10000; i++) {
	list2.add(0, String.valueOf(i));
}

endTime = System.nanoTime();
System.out.println("LinkedList 걸린 시간: " + (endTime - startTime) + "ns");

 

2) Set Interface

- 중복된 element가 발생하지 않도록 내부에서 관리 => 중복허용X

- 정렬되지 않음. => 순서유지X

- 구현 클래스: HashSet, TreeSet

 

HashSet

정렬저장 X

 

TreeSet

정렬저장 O (오름차순)

이진 검색 트리(binary search tree) 의 구조로 되어있음

검색과 정렬에 유리하지만, HashSet보다 데이터 추가, 삭제시간이 더 걸림

 

...더보기

Member.java

public class Member {
	public String name;
	public int age;
	
	public Member(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	/* 
        equals: 최상위 클래스인 Object가 가지고 있는 메소드
        Overriding하여 조건에 맞는 equals 구현 가능
        (ex. HashSet에서 같은 값이면 추가되지 않는 조건 지정 가능)
        */
	public boolean equals(Object obj) {
		if (obj instanceof Member) {
			Member member = (Member) obj;
			 return member.name.equals(name) && (member.age == age);
		} else {
			return false;
		}
	}
	
	// 메모리가 생성된 주소값
	public int hashCode() {
		return this.name.hashCode() + age;
	}
}

 

 

3) Map Interface

- Key와 Value를 매핑하는 객체

- Key는 절대 중복될 수 없음.

- 정렬 기준이 없음.

- 구현 클래스: HashMap, TreeMap ...

 

Hash Map

저장되는 value와 key가 null 허용

동기화가 포함되지 않았으므로 나중에 배우는 multi-thread 환경에서의 구현이 아니라면 Hashtable에 비해서 처리 속도가 빠름.

...더보기

HashTableExample.java

Map<String, String> map = new Hashtable<String, String>();
		
map.put("spring", "12");
map.put("summer", "123");
map.put("fall", "1234");
map.put("winter", "12345");

Scanner sc = new Scanner(System.in);

while (true) {
  System.out.println("아이디와 비밀번호를 입력해주세요.");
  System.out.println("아이디: ");
  String id = sc.nextLine();

  System.out.println("비밀번호:");
  String pw = sc.nextLine();
  System.out.println();

  if (map.containsKey(id)) {
    if (map.get(id).equals(pw)) {
      System.out.println("로그인 되었습니다.");				
      break;
      } else {
      	System.out.println("비밀번호가 일치하지 않습니다.");
      }
    } else {
    	System.out.println("입력하신 아이디가 존재하지 않습니다.");
  }		
}

sc.close();

 

Tree Map

...더보기

TreeMapExample1.java - 원하는 값을 가져오거나, 정렬을 원할 경우 entry로 뽑아옴.

TreeMap<Integer, String> scores = new TreeMap<>();
scores.put(new Integer(87), "홍길동");
scores.put(new Integer(98), "이동수");
scores.put(new Integer(75), "발길순");
scores.put(new Integer(95), "신용권");
scores.put(new Integer(80), "김자바");

Map.Entry<Integer, String> entry = null;

entry = scores.firstEntry();
System.out.println("가장 낮은 점수 : " + entry.getKey() + "-" + entry.getValue());
entry = scores.lastEntry();
System.out.println("가장 높은 점수 : " + entry.getKey() + "-" + entry.getValue());
entry = scores.lowerEntry(new Integer(95));
System.out.println("95점 아래 점수 : " + entry.getKey() + "-" + entry.getValue());
entry = scores.higherEntry(new Integer(95));
System.out.println("95점 위의 점수 : " + entry.getKey() + "-" + entry.getValue());

entry = scores.floorEntry(new Integer(95));
System.out.println("95점 이거나 바로 아래의 점수: " + entry.getKey() + "-" + entry.getValue());
entry = scores.ceilingEntry(new Integer(85));
System.out.println("85점 이거나 바로 위의 점수: " + entry.getKey() + "-" + entry.getValue());

while (!scores.isEmpty()) {
  entry = scores.pollFirstEntry();
  System.out.println(entry.getKey() + "-" + entry.getValue() + "(남은 객체 수 : " + scores.size() + ")");
}

 

TreeMapExample2.java

TreeMap<Integer, String> scores = new TreeMap<>();
scores.put(new Integer(87), "홍길동");
scores.put(new Integer(98), "이동수");
scores.put(new Integer(75), "발길순");
scores.put(new Integer(95), "신용권");
scores.put(new Integer(80), "김자바");

NavigableMap<Integer, String> descendingMap = scores.descendingMap();
Set<Map.Entry<Integer, String>> descendingEntrySet = descendingMap.entrySet();

for (Map.Entry<Integer, String> entry : descendingEntrySet) {
	System.out.print(entry.getKey() + "-" + entry.getValue() + " ");
}

System.out.println();

NavigableMap<Integer, String> ascendingMap = descendingMap.descendingMap(); 	// descending 번갈아가며 수행
Set<Map.Entry<Integer, String>> ascendingEntrySet = ascendingMap.entrySet();

for (Map.Entry<Integer, String> entry : ascendingEntrySet) {
	System.out.print(entry.getKey() + "-" + entry.getValue() + " ");
}

 

Map Collection - Properties 가져오기

public static void main(String[] args) throws FileNotFoundException, IOException{
	
    Properties pt = new Properties();
    String path = PropertiesExample.class.getResource("database.properties").getPath();
	  // /C:/Java%20Programming/Sources/och11/bin/och11/database.properties
    System.out.println("1 path : " + path);		
    path = URLDecoder.decode(path, "utf-8");
    pt.load(new FileReader(path));
    String driver = pt.getProperty("driver");
    String url = pt.getProperty("url");
    String userName = pt.getProperty("username");
    String password = pt.getProperty("password");

	  // /C:/Java Programming/Sources/och11/bin/och11/database.properties
    System.out.println("2 path : " + path);		
    System.out.println("driver: " + driver);
    System.out.println("url1 : " + url);
    System.out.println("username : " + userName);
    System.out.println("password: " + password);
}

 

 

3. Collection Framework의 동기화(synchronization)

추후 예정

 

 

목차

  1. 상속 (클래스간의 관계)
  2. Overriding (메소드 재정의)
  3. final 클래스와 final 메소드
  4. instanceof 연산자
  5. 참조변수와 인스턴스의 연결

1. 상속 (클래스간의 관계)

: 기존의 클래스를 재사용해서 새로운 클래스를 작성부모클래스(객체)의 멤버들을 자식클래스(객체)가 물려받는것

class Parent {}
class Child extends Parent {}

 

  1. 상속을 사용하는 이유 - 기존에 만들어놓은 클래스의 재사용, 확장을 위해 사용. 

  2. 자바에서는 단일상속만이 가능

  3. 부모클래스(super)와 자식클래스(sub)가 존재

  4. Object 클래스 - 모든 클래스의 최상위

    : 모든 클래스는 Object 클래스에 정의된 11개의 메소드를 상속. toString(), equals(Object obj), hashCode() ...

  5. private 객체변수는 상속 안됨

  6. super: 상위 클래스의 멤버나 메소드에 접근하기 위함.

 

2. Override (메소드 재정의)

자식 클래스에서 동일한 매소드를 재정의.

부모 객체의 메소드는 숨겨지기 때문에, 자식 객체에서 메소드를 호출하면 오버라이딩된 자식 메소드가 호출

 

- 접근 제한을 더 강하게 오버라이딩 할 수 없음

- 새로운 예외를 throws할 수 없음

 

 

 

3. final 클래스와 final 메소드

해당 선언이 최종 상태이고, 결코 수정될 수 없음. final 키워드 지정시 상속과 관련됨.

 

- final class: 상속할 수 없는 클래스(ex. String)

- final method: Overriding 할 수 없는 메소드

- final field: 초기값 설정 후, 더 이상 값을 변경할 수 없는 필드

 

 

4. instanceof 연산자

참조변수가 참조하는 인스턴스의 실제 타입을 체크하는데 사용.

if ( c instanceof Car) { ... }

 

 

 

5. 참조변수와 인스턴스의 연결

  • 멤버변수가 중복정의된 경우, 참조변수의 타입에 따라 연결되는 멤버변수가 달라진다. (참조변수타입에 영향받음)
  • 메서드가 중복정의된 경우, 참조변수의 타입에 관계없이 항상 실제 인스턴스의 타입에 정의된 메서드가 호출된다.
    (참조변수타입에 영향받지 않음) -> Overriding

+ Recent posts