JAVA : Collection (2) - Set

keymu·2024년 9월 27일
0

Set:

  • 자료의 중복 저장 허용되지 않음 (hashCode()값의 중복여부!)
  • 저장 순서가 유지되지 않는다. (index 없음)

Hierachy:


HashSet: 매우 빠른 검색(조회) 속도를 제공.

HashSet 인스턴스 생성:

HashSet<Integer> hset = new Hashset<>();

HashSet 종류

hset.add(data);
hset.size();
hset.remove(data);
hset.contains(data);
hset.remove(10);
hset.add(11);
//Set 자료형 변경 방법

다양한 Set Initiazlizer

Set<String> set = new HashSet<>();

// List, 배열로부터 생성
set = new HashSet<>(Arrays.asList("시후", "시후", "최시후"));
ystem.out.println(set);

// Collections utility 클래스 하용
Collections.addAll(set, "절미", "절미", "인절미");
System.out.println(set);

// Stream 사용 (Java8 이상)
set = Stream.of("경민", "경민", "노경민")
	.collect(Collectors.toSet());
System.out.println(set);

// Factory method (Java9 이상)
//set = Set.of("준우", "준우", "박준우"); // of()  에 중복된 값 불가. //IllegalArgumentException
set = Set.of("박", "준", "우");
System.out.println(set);

TreeSet: 데이터가 정렬된 상태로 저장(오름차순, 내림차순)

TreeSet 인스턴스 생성:

TreeSet<Integer> tset = new Treeset<>();

TreeSet 종류

tset.add(data);
//오름차순
Iterator<Integer> itr = tset.iterator();
//내림차순
itr = tset.descendingIterator();
profile
Junior Backend Developer

0개의 댓글