[JAVA]Collections Framework

Ming·2022년 10월 6일
0

자바

목록 보기
12/14

Collections Framework


컬렉션(다수의 객체)를 다루기 위한 표준화된 프로그래밍 방식으로 컬렉션을 쉽고 편리하게 다룰 수 있는 다양한 클래스를 제공한다. 컬렉션 프레임워크에는 List, Set, Map 인터페이스가 있다.

Collection 인터페이스의 메서드

메서드설명
boolean add(Object o)
boolean addAll(Collection c)
지정된 객체(o) 또는 Collection(c)의 객체들을 Collectiondp 추가한다.
void clear()Collection의 모든 객체를 삭제한다.
boolean contains(Object o)
boolean containsAll(Collection c)
지정된 객체 또는 Collection 객체들이 Collection에 포함되어 있는지 확인한다.
boolean equals(Object o)동일한 Collection인지 비교한다
int hashCode()Collection의 hash code를 반환한다
boolean isEmpty()Collection이 비어있는지 확인한다
Iterator iterator()Collection의 iterator를 얻어서 반환한다
boolean remove(Object o)지정된 객체를 삭제한다
boolean removeAll(Collection c)지정된 Collection에 포함된 객체들을 삭제한다
boolean retainAll(Collection c)지정된 Collection에 포함된 객체만을 남기고 다른 객체들은 Collection에서 삭제한다.
이 작업으로 인해 Collection에 변화가 있으면 true 그렇지 않으면 false 반환
int size()Collection에 저장된 객체의 개수를 반환한다
Object[] toArray()Collection에 저장된 객체를 객체배열(Object[])로 반환한다
Object[] toArray(Object[] a)지정된 배열에 Collection의 객체를 저장해서 반환한다

List

  • 순서가 있는 데이터의 집합으로 데이터의 중복을 허용한다.
  • 구현 클래스로는 ArrayList, LinkedList, Stack, Vector 등이 있다.

List인터페이스 메서드

메서드설명
void add(int index, Object element)
boolean addAll(int index, Collection c)
지정된 위치에 객체 또는 컬렉션에 포함된 객체들을 추가
Object get(int index)지정된 위치에 있는 객체 반환
int indexOf(Object o)지정된 객체의 위치를 반환(첫번째 요소부터 순방향으로)
int lastIndexOf(Object o)지정된 객체의 위치를 반환(마지막요소부터 역방향으로
Object remove(int index)지정된 위치에 있는 객체를 삭제하고 삭제된 객체를 반환
Object set(int index, Object element)지정된 위치에 객체를 저장
void sort(Comparator c)지정된 비교자로 List 정렬
List subList(int fromIndex, int toIndex)지정된 범위에 있는 객체를 반환

ArrayList

저장순서가 유지되고 중복을 허용하며 데이터 저장공간으로 배열을 사용한다.

  • 추가 : add와 addAll 메서드
  • 삭제 : remove와 clear 메서드(clear는 전체 삭제)
  • 검색
    • int indexOf(Object o), int lastIndexOf(Object o) : 존재하면 index 반환, 없으면 -1 반환(lastIndexOf는 제일 뒤부터 검색)
    • boolean contains(Object o) : 객체가 존재하면 true, 존재하지 않으면 false 반환
    • Object get(int index) : 특정 위치에 있는 객체 반환
    • Object set(int index, Object element) : 특정 위치에 있는 객체 변경
      ArrayList 생성
ArrayList<Integer> integers1 = new ArrayList<Integer>(); // 타입 지정
ArrayList<Integer> integers2 = new ArrayList<>(); // 타입 생략 가능
ArrayList<Integer> integers3 = new ArrayList<>(10); // 초기 용량 설정
ArrayList<String> colors = new ArrayList<>(Arrays.asList("Blue", "Black", "White", "Red"));

ArrayList element 추가/변경

ArrayList<String> colors = new ArrayList<>();
        
//추가
colors.add("Black");
colors.add("White");
colors.add(0, "Green"); //0번째에 Green 추가
colors.add("Red");

// 변경
colors.set(0, "Blue"); //0번째 Blue로 변경

System.out.println(colors);
[Blue, Black, White, Red]

ArrayList elements 제거

ArrayList<String> colors = new ArrayList<>(Arrays.asList("Blue", "Black", "White", "Red"));
colors.remove(0); //0번째 인덱스 값 제거
System.out.println(colors);

colors.remove("Black");//Black 제거
System.out.println(colors);

colors.clear(); //전체 삭제
[Black, White, Red]
[White, Red]

ArrayList elements 존재 유무

ArrayList<String> colors = new ArrayList<>(Arrays.asList("Black", "White", "Green", "Red", "Black"));

boolean contains = colors.contains("Black"); //존재하면 true, 존재하지 않으면 false
System.out.println(contains);

int index = colors.indexOf("Green"); //존재하는 인덱스 값 반환, 존재하지 않으면 -1
System.out.println(index);

index = colors.lastIndexOf("Black");//뒤에서부터 역방향으로 찾아보며 존재하는 인덱스 값 반환, 존재하지 않으면 -1
System.out.println(index);
index = colors.lastIndexOf("Blue");
System.out.println(index);
true
2
4
-1

Set

  • 순서를 유지하지 않는 데이터의 집합으로 데이터의 중복을 허용하지 않는다. - 구현 클래스로는 HashSet, TreeSet 등이 있다.
  • Set 인터페이스의 메서드는 Collection 인터페이스와 동일하다

집합과 관련된 메서드

Collection에 변화가 있으면 true, 아니면 false를 반환한다.

메서드설명
boolean addAll(Collection c)지정된 Collection의 객체들을 Collection에 추가(합집합)
boolean containsAll(Collection c)지정된 Collection의 객체들이 Collection에 포함되어 있는지 확인(부분집합)
boolean removeAll(Collection c)지정된 Collection에 포함된 객체들을 삭제(차집합)
boolean retainAll(Collectoin c)지정된 Collection에 포함된 객체들만 남기고 나머지는 삭제(교집합)

HashSet

Set 인터페이스를 구현한 대표적인 컬렉션 클래스이고 순서를 유지하려면 LinkedHashSet클래스를 사용하면 된다.

  • 추가 : add, addAll(합집합)
  • 삭제 : remove, removeAll(교집합), clear, retainAll(차집합)
  • 포함 : contains, containsAll
    HashSet 생성
HashSet<String> colors1 = new HashSet<String>(); // 타입 지정
HashSet<String> colors2 = new HashSet<>(); // 타입 생략 가능
HashSet<String> colors3 = new HashSet<>(10); // 초기 용량 설정
HashSet<String> colors4 = new HashSet<>(Arrays.asList("Blue", "Black", "White"));

HashSet element 추가

HashSet<String> colors = new HashSet<>();
colors.add("Black");
colors.add("White");
colors.add("Green");
colors.add("Red");
colors.add("White");

System.out.println(colors);
[Red, White, Black, Green]

중복되는 값은 제거 되기 때문에 White가 하나만 들어가 있는 것을 확인할 수 있다.
HashSet element 삭제

HashSet<String> colors = new HashSet<>(Arrays.asList("Blue", "Black", "White", "Red", "Green"));

colors.remove("Red"); //[White, Blue, Black, Green]
color.removeAll(Arrays.asList("White", "Blue")); //[Black, Green]

HashSet element 전체 출력

HashSet<String> colors = new HashSet<>(Arrays.asList("Blue", "Black", "White", "Red", "Green"));

for (String color : colors) {
	System.out.print(color + "  ");
}
System.out.println();

//Iterator 이용
Iterator it = colors.iterator();
while(it.hasNext()) {
	System.out.print(it.next());
}
Red  White  Blue  Black  Green  
Red White Blue Black Green 

값 존재 유무

HashSet<String> colors = new HashSet<>(Arrays.asList("Blue", "Black", "White", "Red", "Green"));
System.out.println(colors.contains("Green")); // true
System.out.println(colors.contains("Yellow")); // false

Map

  • 키(key)와 값(value)의 쌍으로 이루어진 데이터의 집합
  • 순서는 유지되지 않으며, 키는 중복을 허용하지 않고, 값은 중복을 허용한다. - 구현클래스로는 HashMap, TreeMap, Hashtable, Properties 등이 있다.

Map 인터페이스 메서드

메서드설명
Object put(Object key, Object value)Map에 value 객체를 key객체에 연결하여 저장
void putAll(Map t)지정된 Map의 모든 key-value 쌍을 추가
boolean containsKey(Object kdy)지정된 key객체와 일치하는 Map의 keyr객체가 있는지 확인
boolean containsValue(Object value)지정된 value 객체와 일치하는 Map의 value객체가 있는지 확인
Object get(Object key)지정된 key객체에 대응하는 value 객체를 찾아서 반환
Set entrySet()Map에 저장되어 있는 key-value 쌍을 Map.Entry타입의 객체로 저장한 Set으로 반환

HashMap

HashMap은 키와 값으로 구성된 Entry객체를 저장하는 구조를 가지고 있는 자료구조인 Map의 성질을 그대로 갖고 있다. 여기서 키와 값은 모두 객체이고, 값은 중복 저장될 수 있지만 키는 중복 저장될 수 없다. 만약 기존에 저장된 키와 동일한 키로 값을 저장하면 기존의 값은 없어지고 새로운 값으로 대치된다
HashMap 생성

HashMap<String,String> map1 = new HashMap<String,String>();//HashMap생성
HashMap<String,String> map2 = new HashMap<>();//new에서 타입 파라미터 생략가능
HashMap<String,String> map3 = new HashMap<>(map1);//map1의 모든 값을 가진 HashMap생성
HashMap<String,String> map4 = new HashMap<>(10);//초기 용량(capacity)지정
HashMap<String,String> map5 = new HashMap<>(10, 0.7f);//초기 capacity,load factor지정
HashMap<String,String> map6 = new HashMap<String,String>(){{//초기값 지정
    put("a","b");
}};

HashMap element 추가

HashMap<Integer,String> colors = new HashMap<>();//new에서 타입 파라미터 생략가능
colors.put(1,"Black"); //값 추가
colors.put(2,"Blue");
colors.put(3,"Green");

HashMap element 삭제

HashMap<Integer,String> colors = new HashMap<Integer,String>(){{//초기값 지정
    put(1,"Black");
    put(2,"Blue");
    put(3,"Green");
    put(4, "Red");
}};
map.remove(1); //key값 1 제거(Black 제거)
map.clear(); //모든 값 제거

HashMap element 출력

HashMap<Integer,String> colors = new HashMap<Integer,String>(){{//초기값 지정
            put(1,"Black");
            put(2,"Blue");
            put(3,"Green");
            put(4, "Red");
        }};

System.out.println(colors); //{1=Black, 2=Blue, 3=Green, 4=Red}
System.out.println(colors.get(3)); //Green

for(Map.Entry<Integer, String> entry : colors.entrySet()){
	System.out.println("key : "+entry.getKey()+" value : "+entry.getValue());
}
 /*결과 
key : 1 value : Black
key : 2 value : Blue
key : 3 value : Green
key : 4 value : Red
*/

HashMap iterator

HashMap<Integer,String> colors = new HashMap<Integer,String>(){{//초기값 지정
            put(1,"Black");
            put(2,"Blue");
            put(3,"Green");
            put(4, "Red");
}};

Iterator<Map.Entry<Integer, String>> entries = colors.entrySet().iterator();
while(entries.hasNext()){
	Map.Entry<Integer, String> entry = entries.next();
	System.out.println("[Key]:" + entry.getKey() + " [Value]:" +  entry.getValue());
}

//keySet().iterator()
Iterator<Integer> keys = colors.keySet().iterator();
while(keys.hasNext()){
	int key = keys.next();
	System.out.println("[Key]:" + key + " [Value]:" +  colors.get(key));
}
/* 둘다 결과 동일
[Key]:1 [Value]:Black
[Key]:2 [Value]:Blue
[Key]:3 [Value]:Green
[Key]:4 [Value]:Red
*/

0개의 댓글