Java: TreeSet

new-powยท2022๋…„ 11์›” 8์ผ
0

TreeSet ํด๋ž˜์Šค

๐Ÿ‘€ ํŠน์ง•

  • ๊ฐ์ฒด์˜ ์ •๋ ฌ์— ์‚ฌ์šฉ๋˜๋Š” ํด๋ž˜์Šค
  • ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š์œผ๋ฉฐ(set) ์˜ค๋ฆ„์ฐจ์ˆœ์ด๋‚˜ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ •๋ ฌํ•œ๋‹ค.
  • ์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ(binary search tree)๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ๋‹ค.
  • ๊ฐ์ฒด ๋น„๊ต๋ฅผ ์œ„ํ•ด Comparable ์ด๋‚˜ Comparator ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ ํ•œ๋‹ค.

๐Ÿ”จ ์ƒ์„ฑ๊ณผ ์ฃผ์š” ๋ฉ”์†Œ๋“œ

์ƒ์„ฑ

Treeset<String> treeSet = new TreeSet<String>();

์š”์†Œ ์ถ”๊ฐ€

treeSet.add(str); // ์ถ”๊ฐ€

์š”์†Œ ์ œ๊ฑฐ

treeSet.remove(0);

์š”์†Œ ์ •๋ ฌ

Comparable

  • ์ฃผ์˜!! ํด๋ž˜์Šค๋กœ ์ƒˆ๋กœ ์ •์˜๋œ ๊ฐ์ฒด์˜ ๊ฒฝ์šฐ ์–ด๋–ป๊ฒŒ ๋น„๊ตํ•ด์„œ ๋„ฃ์„์ง€ ๊ตฌํ˜„์„ ๊ฐ™์ด ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.
  • ๊ธฐ๋ณธ ์ž๋ฃŒํ˜•์—๋Š” Comparable ๊ฐ€ ์ด๋ฏธ ๊ตฌํ˜„๋˜์–ด ์žˆ๋‹ค.
public class Member implements Comparable<Member> {

  @Override
  public int compareTo(Member member){
      // ๊ธฐ์กด ๊ฒƒ๊ณผ ๋น„๊ตํ•  ๊ฒƒ์„ ๊ตฌํ˜„ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.
      return (this.memberId - member.memberId);
  }
 
 }
  • return ๊ฐ’์ด
    - ์–‘์ˆ˜ = memberId๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
    - ์Œ์ˆ˜ = memberId๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

Comparator

  • ๋ณดํ†ต์€ Comparable์„ ์‚ฌ์šฉํ•˜์ง€๋งŒ... ๊ทธ๋ž˜๋„ ์ •๋ฆฌํ•ด๋‘๊ธฐ!
  • ์ฃผ์˜! ์‚ฌ์šฉ ์ „์— ์ƒ์„ฑ์ž์— Default Construcktor ๋งŒ๋“ค์–ด๋‘์–ด์•ผ ํ•œ๋‹ค.
Treeset<Member> treeSet = new TreeSet<Member>(new Member());
// ํ˜น์€ ๋‹ค๋ฅธ compare๊ฐ€ ์žˆ๋Š” ํด๋ž˜์Šค๋„ ๊ฐ€๋Šฅ

public class Member implements Comparator<Member> {

  @Override
  public int compare(Member member1, Member member2){
      // member1 == ๊ธฐ์กด ๊ฒƒ
      // member2 == ์ƒˆ๋กœ ๋“ค์–ด์˜จ ๊ฒƒ
      // ๊ธฐ์กด ๊ฒƒ๊ณผ ๋น„๊ตํ•  ๊ฒƒ์„ ๊ตฌํ˜„ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.
      return (member1.memberId - member2.memberId);
  }
 
 }
  • return ๊ฐ’์ด
    - ์–‘์ˆ˜ = memberId๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
    - ์Œ์ˆ˜ = memberId๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

๐Ÿ‘ฟ ๊ด€๋ จ ๋ฌธ์ œ


๐Ÿ–‡๏ธ ์ฐธ๊ณ  ์ž๋ฃŒ

  • Do it! ์ž๋ฐ” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์ž…๋ฌธ
profile
์ €๋Š” ๋ธ”๋กœ๊ทธ ์ด์‚ฌ๋ฅผ ๊ฐ”์Šต๋‹ˆ๋‹ค

0๊ฐœ์˜ ๋Œ“๊ธ€