Ръководство за TreeSet в Java

1. Общ преглед

В тази статия ще разгледаме неразделна част от Java Collections Framework и една от най-популярните реализации на Set - TreeSet .

2. Въведение в TreeSet

Най-просто казано, TreeSet е сортирана колекция, която разширява класа AbstractSet и реализира интерфейса NavigableSet .

Ето кратко обобщение на най-важните аспекти на това изпълнение:

  • Съхранява уникални елементи
  • Той не запазва реда на вмъкване на елементите
  • Той сортира елементите във възходящ ред
  • Не е безопасно за нишки

При това изпълнение обектите се сортират и съхраняват във възходящ ред според естествения им ред . В TreeSet използва самобалансиращо двоично дърво за търсене, по-специално с червено-черно дърво.

Най-просто казано, като самобалансиращо се двоично дърво за търсене, всеки възел на двоичното дърво се състои от допълнителен бит, който се използва за идентифициране на цвета на възела, който е или червен, или черен. По време на следващите вмъквания и изтривания тези „цветни“ битове помагат да се гарантира, че дървото остава повече или по-малко балансирано.

И така, нека създадем екземпляр на TreeSet :

Set treeSet = new TreeSet();

2.1. TreeSet с конструктор за сравнение Param

По желание можем да конструираме TreeSet с конструктор, който ни позволява да дефинираме реда, в който елементите се сортират с помощта на Comparable или Comparator:

Set treeSet = new TreeSet(Comparator.comparing(String::length));

Въпреки че TreeSet не е безопасен за нишки, той може да се синхронизира външно с помощта на обвивката Collections.synchronizedSet () :

Set syncTreeSet = Collections.synchronizedSet(treeSet);

Добре, сега, когато имаме ясна представа за това как да създадем екземпляр TreeSet , нека да разгледаме често срещаните операции, с които разполагаме.

3. TreeSet add ()

Методът add () , както се очаква, може да се използва за добавяне на елементи към TreeSet . Ако е добавен елемент, методът връща true, в противен случай - false.

Договорът на метода гласи, че елемент ще бъде добавен само когато същият вече не присъства в Set .

Нека добавим елемент към TreeSet :

@Test public void whenAddingElement_shouldAddElement() { Set treeSet = new TreeSet(); assertTrue(treeSet.add("String Added")); }

Методът на добавяне е изключително важен, тъй като подробностите за изпълнението на метода илюстрират как TreeSet работи вътрешно , как използва метода на пускането на TreeMap за съхраняване на елементите:

public boolean add(E e) { return m.put(e, PRESENT) == null; }

Променливата m се отнася до вътрешна подкрепяща TreeMap (имайте предвид, че TreeMap реализира NavigateableMap ):

private transient NavigableMap m;

Следователно TreeSet вътрешно зависи от подкрепяща NavigableMap, която се инициализира с екземпляр на TreeMap, когато е създаден екземпляр на TreeSet :

public TreeSet() { this(new TreeMap()); }

Повече за това можете да намерите в тази статия.

4. TreeSet съдържа ()

Методът contains () се използва за проверка дали даден елемент присъства в даден TreeSet . Ако елементът бъде намерен, той връща true, иначе false.

Нека да видим съдържанието () в действие:

@Test public void whenCheckingForElement_shouldSearchForElement() { Set treeSetContains = new TreeSet(); treeSetContains.add("String Added"); assertTrue(treeSetContains.contains("String Added")); }

5. TreeSet remove ()

Методът remove () се използва за премахване на посочения елемент от набора, ако той присъства.

Ако набор съдържа указания елемент, този метод връща true.

Нека го видим в действие:

@Test public void whenRemovingElement_shouldRemoveElement() { Set removeFromTreeSet = new TreeSet(); removeFromTreeSet.add("String Added"); assertTrue(removeFromTreeSet.remove("String Added")); }

6. TreeSet clear ()

Ако искаме да премахнем всички елементи от набор, можем да използваме метода clear () :

@Test public void whenClearingTreeSet_shouldClearTreeSet() { Set clearTreeSet = new TreeSet(); clearTreeSet.add("String Added"); clearTreeSet.clear(); assertTrue(clearTreeSet.isEmpty()); }

7. Размер на TreeSet ()

Методът size () се използва за идентифициране на броя на елементите, присъстващи в TreeSet . Това е един от основните методи в API:

@Test public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() { Set treeSetSize = new TreeSet(); treeSetSize.add("String Added"); assertEquals(1, treeSetSize.size()); }

8. TreeSet isEmpty ()

Методът isEmpty () може да се използва, за да се разбере дали даден екземпляр TreeSet е празен или не:

@Test public void whenCheckingForEmptyTreeSet_shouldCheckForEmpty() { Set emptyTreeSet = new TreeSet(); assertTrue(emptyTreeSet.isEmpty()); }

9. Итератор TreeSet ()

The iterator() method returns an iterator iterating in the ascending order over the elements in the Set. Those iterators are fail-fast.

We can observe the ascending iteration order here:

@Test public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() { Set treeSet = new TreeSet(); treeSet.add("First"); treeSet.add("Second"); treeSet.add("Third"); Iterator itr = treeSet.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }

Additionally, TreeSet enables us to iterate through the Set in descending order.

Let's see that in action:

@Test public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() { TreeSet treeSet = new TreeSet(); treeSet.add("First"); treeSet.add("Second"); treeSet.add("Third"); Iterator itr = treeSet.descendingIterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }

The Iterator throws a ConcurrentModificationException if the set is modified at any time after the iterator is created in any way except through the iterator's remove() method.

Let's create a test for this:

@Test(expected = ConcurrentModificationException.class) public void whenModifyingTreeSetWhileIterating_shouldThrowException() { Set treeSet = new TreeSet(); treeSet.add("First"); treeSet.add("Second"); treeSet.add("Third"); Iterator itr = treeSet.iterator(); while (itr.hasNext()) { itr.next(); treeSet.remove("Second"); } } 

Alternatively, if we had used the iterator's remove method, then we wouldn't have encountered the exception:

@Test public void whenRemovingElementUsingIterator_shouldRemoveElement() { Set treeSet = new TreeSet(); treeSet.add("First"); treeSet.add("Second"); treeSet.add("Third"); Iterator itr = treeSet.iterator(); while (itr.hasNext()) { String element = itr.next(); if (element.equals("Second")) itr.remove(); } assertEquals(2, treeSet.size()); }

There's no guarantee on the fail-fast behavior of an iterator as it's impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.

More about this can be found here.

10. TreeSet first()

This method returns the first element from a TreeSet if it's not empty. Otherwise, it throws a NoSuchElementException.

Let's see an example:

@Test public void whenCheckingFirstElement_shouldReturnFirstElement() { TreeSet treeSet = new TreeSet(); treeSet.add("First"); assertEquals("First", treeSet.first()); }

11. TreeSet last()

Analogously to the above example, this method will return the last element if the set is not empty:

@Test public void whenCheckingLastElement_shouldReturnLastElement() { TreeSet treeSet = new TreeSet(); treeSet.add("First"); treeSet.add("Last"); assertEquals("Last", treeSet.last()); }

12. TreeSet subSet()

This method will return the elements ranging from fromElement to toElement. Note that fromElement is inclusive and toElement is exclusive:

@Test public void whenUsingSubSet_shouldReturnSubSetElements() { SortedSet treeSet = new TreeSet(); treeSet.add(1); treeSet.add(2); treeSet.add(3); treeSet.add(4); treeSet.add(5); treeSet.add(6); Set expectedSet = new TreeSet(); expectedSet.add(2); expectedSet.add(3); expectedSet.add(4); expectedSet.add(5); Set subSet = treeSet.subSet(2, 6); assertEquals(expectedSet, subSet); }

13. TreeSet headSet()

This method will return elements of TreeSet which are smaller than the specified element:

@Test public void whenUsingHeadSet_shouldReturnHeadSetElements() { SortedSet treeSet = new TreeSet(); treeSet.add(1); treeSet.add(2); treeSet.add(3); treeSet.add(4); treeSet.add(5); treeSet.add(6); Set subSet = treeSet.headSet(6); assertEquals(subSet, treeSet.subSet(1, 6)); }

14. TreeSet tailSet()

This method will return the elements of a TreeSet which are greater than or equal to the specified element:

@Test public void whenUsingTailSet_shouldReturnTailSetElements() { NavigableSet treeSet = new TreeSet(); treeSet.add(1); treeSet.add(2); treeSet.add(3); treeSet.add(4); treeSet.add(5); treeSet.add(6); Set subSet = treeSet.tailSet(3); assertEquals(subSet, treeSet.subSet(3, true, 6, true)); }

15. Storing Null Elements

Before Java 7, it was possible to add null elements to an empty TreeSet.

However, that was considered a bug. Therefore, TreeSet no longer supports the addition of null.

When we add elements to the TreeSet, the elements get sorted according to their natural order or as specified by the comparator. Hence adding a null, when compared to existing elements, results in a NullPointerException since null cannot be compared to any value:

@Test(expected = NullPointerException.class) public void whenAddingNullToNonEmptyTreeSet_shouldThrowException() { Set treeSet = new TreeSet(); treeSet.add("First"); treeSet.add(null); }

Elements inserted into the TreeSet must either implement the Comparable interface or at least be accepted by the specified comparator. All such elements must be mutually comparable,i.e.e1.compareTo(e2) or comparator.compare(e1, e2)mustn't throw a ClassCastException.

Let's see an example:

class Element { private Integer id; // Other methods... } Comparator comparator = (ele1, ele2) -> { return ele1.getId().compareTo(ele2.getId()); }; @Test public void whenUsingComparator_shouldSortAndInsertElements() { Set treeSet = new TreeSet(comparator); Element ele1 = new Element(); ele1.setId(100); Element ele2 = new Element(); ele2.setId(200); treeSet.add(ele1); treeSet.add(ele2); System.out.println(treeSet); }

16. Performance of TreeSet

When compared to a HashSet the performance of a TreeSet is on the lower side. Operations like add, remove and search take O(log n) time while operations like printing n elements in sorted order require O(n) time.

A TreeSet should be our primary choice if we want to keep our entries sorted as a TreeSet may be accessed and traversed in either ascending or descending order, and the performance of ascending operations and views is likely to be faster than that of descending ones.

The Principle of Locality – is a term for the phenomenon in which the same values, or related storage locations, are frequently accessed, depending on the memory access pattern.

When we say locality:

  • Similar data is often accessed by an application with similar frequency
  • If two entries are nearby given an ordering, a TreeSet places them near each other in the data structure, and hence in memory

A TreeSet being a data-structure with greater locality we can, therefore, conclude in accordance to the Principle of Locality, that we should give preference to a TreeSet if we're short on memory and if we want to access elements that are relatively close to each other according to their natural ordering.

В случай, че данните трябва да бъдат прочетени от твърдия диск (който има по-голяма латентност от данните, прочетени от кеша или паметта), предпочитайте TreeSet, тъй като има по-голяма локалност

17. Заключение

В тази статия ние се фокусираме върху разбирането как да използваме стандартната реализация на TreeSet в Java. Видяхме неговата цел и колко ефикасна е по отношение на използваемостта, като се има предвид способността му да избягва дублиране и сортиране на елементи.

Както винаги, кодови фрагменти могат да бъдат намерени в GitHub.