CodeGym /Java Blog /무작위의 /Java의 LinkedHashSet
John Squirrels
레벨 41
San Francisco

Java의 LinkedHashSet

무작위의 그룹에 게시되었습니다
Java의 LinkedHashSet 클래스 에 대해 말하자면 Set 인터페이스 를 구현한다는 점을 언급해야 합니다 . LinkedHashSet은 해시 테이블에 요소를 저장하는 컬렉션을 생성하지만 해당 HashSet 대응 요소와 달리 요소의 삽입 순서를 유지합니다.

Java에서 설정되는 것

Set 인터페이스가 집합(집합)을 정의한다는 것을 간단히 기억해 봅시다 . 컬렉션을 확장 하고 중복 요소를 허용하지 않는 컬렉션의 동작을 정의합니다. 따라서 add() 메서드는 집합에 중복 요소를 추가하려고 하면 false를 반환합니다. 인터페이스는 자체적으로 추가 메서드를 정의하지 않습니다. Set 인터페이스는 저장된 객체의 고유성을 관리하며 고유성 equals() 메서드 의 구현에 의해 결정됩니다 . 따라서 생성된 클래스의 객체를 Set 에 추가할 경우 equals() 메서드를 오버라이드하는 것이 바람직하다 .

LinkedHashSet 클래스

LinkedHashSet 클래스 에 대해 이야기하기 전에 가까운 친척인 HashSet 클래스 를 언급해야 합니다 . HashSet은 Set 인터페이스를 구현합니다 . 해시 테이블에 요소를 저장하는 컬렉션을 만듭니다. 해시 테이블의 요소는 키-값 쌍으로 저장됩니다. 키는 값을 저장할 셀(또는 세그먼트)을 지정합니다. 키의 내용은 해시 코드라는 고유한 값을 결정하는 데 사용됩니다. 해시 코드가 고유할 필요는 없지만 개체 식별자로 생각할 수 있습니다. 이 해시 코드는 키와 관련된 데이터가 저장되는 인덱스 역할도 합니다. LinkedHashSet Java 클래스는 메서드를 추가하지 않고 HashSet을 확장합니다.LinkedHashSet을 사용하면 HashSet 과 마찬가지로 항목의 존재를 빠르게 확인할 수 있지만 내부에 정렬된 목록이 포함되어 있습니다. 즉, 요소의 삽입 순서를 저장합니다. 즉, LinkedHashSet은 삽입된 순서대로 집합 요소의 연결된 목록을 유지합니다. 이렇게 하면 세트에 순서대로 삽입할 수 있습니다. 그러나 이로 인해 LinkedHashSet 클래스가 HashSet 클래스 보다 더 긴 작업을 수행하게 됩니다 .

LinkedHashSet의 중요한 기능

  • LinkedHashSet 에만 고유한 요소를 저장할 수 있습니다.

  • LinketHashSet을 사용하면 삽입한 순서대로 요소를 추출할 수 있습니다.

  • LinkedHashSet이 동기화되지 않음

  • LinkedHashSet은 null 요소를 저장할 수 있습니다.

  • LinkedHashSet은 해싱 기술을 사용하여 해시 코드를 기반으로 지정된 인덱스에 요소를 저장합니다.

LinkedHashSet 메서드

부모 클래스에서 상속된 메서드 외에도 HashSet은 다음 메서드를 정의합니다.
  • boolean add(Object o)는 지정된 요소가 아직 존재하지 않는 경우 이 세트에 추가합니다.

  • void clear()는 이 세트에서 모든 요소를 ​​제거합니다.

  • Object clone()은 이 LinkedHashSet 인스턴스 의 얕은 복사본을 반환합니다 . 요소 자체는 복제되지 않습니다.

  • boolean contains(Object o)는 이 집합에 지정된 요소가 포함되어 있으면 true를 반환합니다.

  • 부울 isEmpty()는 이 집합에 요소가 없으면 true를 반환합니다 .

  • Iterator iterator()는 이 집합의 요소에 대한 반복자를 반환합니다.

  • boolean remove(Object o)는 이 세트에서 지정된 요소를 제거합니다(존재하는 경우).

  • int size()는 이 집합의 요소 수(요소 수)를 반환합니다.

쉬운 LinkedHashSet 예제 아래 예제에서는 LinkedHashSet 개체의 초기화와 add() 메서드를 사용하여 집합을 채우는 방법을 보여줍니다.

import java.util.LinkedHashSet;
import java.util.Set;

   public class LinkedHashSetEx1 {
       public static void main(String[] args) {
//LinkedHashSet() Init            
Set<String> set = new LinkedHashSet<>();
//adding elements to LinkedHashSet 
           set.add("Re"); //first added element 
           set.add("Do");
           set.add("Fa");
           set.add("Sol");
           set.add("La");
           set.add("Ti");
           set.add("Mi");//last added element  


           System.out.println(set);
       }
   }
출력은 다음과 같습니다.
[레, 도, 파, 솔, 라, 티, 미]
보시다시피 세트의 요소는 배치한 것과 동일한 순서로 나타납니다. Java의 LinkedHashSet - 1

예 2. LinkedHashSet에 복제 항목 추가

악보 이름이 있는 LinkedHashSet 7 요소를 다시 넣고 이전에 배치한 요소 중 하나와 동일한 새 요소를 하나 넣습니다.

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetEx2 {
   public static void main(String[] args) {
           Set<String> set = new LinkedHashSet<>();
           set.add("Re");
           set.add("Do");
           set.add("Fa");
           set.add("Sol");
           set.add("La");
           set.add("Ti");
           set.add("Mi");
           set.add("Sol");
           System.out.println(set);
       }
   }
프로그램의 출력은 다음과 같습니다.
[레, 도, 파, 솔, 라, 티, 미]
예제 2의 출력은 첫 번째 예제와 완전히 동일합니다. LinkedHashSet 컬렉션 에는 두 개의 유사한 요소가 있을 수 없습니다 . 두 번째 것을 넣으려고 하면 그냥 무시됩니다.

예 3. LinkedHashSet에서 요소 제거


import java.util.LinkedHashSet;
import java.util.Set;
   public class LinkedHashSet3 {
       public static void main(String[] args) {
           Set<String> set = new LinkedHashSet<>();
           set.add("Re");
           set.add("Do");
           set.add("Fa");
           set.add("Sol");
           set.add("La");
           set.add("Ti");
           set.add("Mi");
           System.out.println(set);
           set.remove("Fa");// removing an element from our set
           set.remove("Score");//trying to remove element that isn't in set
           System.out.println(set.remove("Score"));
           System.out.println("Print our set without elements removed: ");
           System.out.println(set);
           set.clear();
           System.out.println("Print out our set after clear command: ");
           System.out.println(set);
       }
   }
프로그램의 출력은 다음과 같습니다.
[Re, Do, Fa, Sol, La, Ti, Mi] false 제거된 요소 없이 세트 인쇄: [Re, Do, Sol, La, Ti, Mi] 지우기 명령 후 세트 인쇄: []
보다 시피 존재하지 않는 요소에 적용된 remove() 메서드는 프로그램 오류를 일으키지 않습니다. 요소가 제거되지 않은 경우 단순히 false를 반환하고 요소가 LinkedHashSet 에 있다가 제거된 경우 true를 반환합니다 .

LinkedHashSet 대 HashSet

이 두 클래스는 가까운 친척입니다. 그러나 HashSet 내부에서는 HashMap을 사용하여 개체를 저장하고 LinkedHashSet은 LinkedHashMap을 사용합니다 . 삽입 순서를 유지할 필요가 없지만 고유한 개체를 저장해야 하는 경우 HashSet을 사용하는 것이 더 적합합니다 . 요소의 삽입 순서를 유지해야 하는 경우 LinkedHashSet을 선택합니다. LinkedHashSet은 내부 LinkedList를 사용하여 요소의 삽입 순서를 유지하기 때문에 LinkedHashSet 의 성능은 HashSet 보다 약간 느립니다 . 예를 들어 보겠습니다.

import java.util.*;

public class LinkedHashSetExample1 {

   public static void main(String[] args) {
       // while regular hash set orders its elements according to its hashcode stamps

       Set<Integer> regularHashSet = new HashSet<>();
       regularHashSet.add(7);
       regularHashSet.add(3);
       regularHashSet.add(5);
       regularHashSet.add(65536);
       regularHashSet.add(9);
       // few duplicates
       regularHashSet.add(5);
       regularHashSet.add(7);

       // next will print:
       // > regularHashSet = [65536, 3, 5, 7, 9]
       System.out.println("regularHashSet = " + regularHashSet);

       // linked hash set keeps order of adding unchanged

       Set<Integer> linkedHashSet = new LinkedHashSet<>();
       linkedHashSet.add(7);
       linkedHashSet.add(3);
       linkedHashSet.add(5);
       linkedHashSet.add(65536);
       linkedHashSet.add(9);
       // few duplicates
       linkedHashSet.add(5);
       linkedHashSet.add(7);

       // next will print:
       // > linkedHashSet = [7, 3, 5, 65536, 9]
       System.out.println("linkedHashSet = " + linkedHashSet);
   }
}
프로그램의 출력은 다음과 같습니다.
regularHashSet = [65536, 3, 5, 7, 9] linkedHashSet = [7, 3, 5, 65536, 9]

실제 애플리케이션에서 Java LinkedHashSet 사용

LinkedHashSet을 사용하면 항목의 존재를 빠르게 확인하고 주문도 저장할 수 있으므로 이 컬렉션은 목록에서 중복 항목을 제거하는 데 매우 편리해 보입니다. 또는 예를 들어 내 가방에서 가장 최근에 본 항목과 같은 문제를 해결합니다. 아니면 그런 게임, Pokemon Go를 기억하십니까? LinkedHashSet은 당신이 만난 포켓몬 목록과 그들이 당신의 경로에서 만난 순서를 저장할 수 있습니다. 이 경우 "반복" 포켓몬은 더 이상 목록에 추가되지 않습니다. 또는 예를 들어 레벨이 있는 모든 게임에서 이미 만난 레벨별 보스 목록입니다. 또는 천체 발견의 역사. LinkedHashSet공간 본체가 이미 목록에 있는지 여부를 빠르게 확인하고 목록에 없는 경우 목록에 추가할 수 있습니다. 중복 제거의 예를 들어 보겠습니다.

import java.util.*;

class LinkedHashSetExample2 {
   public static void main(String[] args) {
       List<String> listWithDuplicates = List.of("some","elements","with", "few", "duplicates", "were", "here", "duplicates", "duplicates");

       Set<String> linkedHashSet = new LinkedHashSet<>(listWithDuplicates);
       List<String> listWithoutDuplicates = new ArrayList<>(linkedHashSet);

       // next will print:
       // > listWithDuplicates = [some, elements, with, few, duplicates, here, duplicates, duplicates]
       System.out.println("listWithDuplicates = " + listWithDuplicates);
       // next will print:
       // > listWithoutDuplicates = [some, elements, with, few, duplicates, here]
       System.out.println("listWithoutDuplicates = " + listWithoutDuplicates);

       // -------------------------------------------------------------------------

       // while using regular Hash Set will generally produces some unexpected order
       Set<String> regularHashSet = new HashSet<>(listWithDuplicates);

       // next will print:
       // > linkedHashSet = [some, elements, with, few, duplicates, were, here]
       System.out.println("linkedHashSet = " + linkedHashSet);
       // next will print:
       // > regularHashSet = [here, some, with, duplicates, were, elements, few]
       System.out.println("regularHashSet = " + regularHashSet);
   }
}
프로그램의 출력은 다음과 같습니다.
listWithDuplicates = [some, elements, with, few, duplicates, were, here, duplicates, duplicates] listWithoutDuplicates = [some, elements, with, few, duplicates, were, here] linkedHashSet = [some, elements, with, few, duplicates , 있었다, 여기] regularHashSet = [여기, 일부, 와, 중복, 있었다, 요소, 소수]
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION