1. Przegląd
Krotka to zbiór kilku elementów, które mogą, ale nie muszą być ze sobą powiązane. Innymi słowy, krotki można uznać za obiekty anonimowe.
Na przykład [„RAM”, 16, „Astra”] to krotka zawierająca trzy elementy.
W tym artykule przyjrzymy się bardzo prostej bibliotece, która pozwala nam pracować ze strukturami danych opartymi na krotkach o nazwie javatuples .
2. Wbudowane klasy Javatuples
Ta biblioteka zapewnia nam dziesięć różnych klas, które wystarczyłyby większość naszych wymagań związanych z krotkami:
- Jednostka
- Para
- Tryplet
- Kwartet
- Kwintet
- Sekstet
- Septet
- Oktet
- Ennead
- Dekada
Oprócz powyższych klas istnieją dwie dodatkowe klasy, KeyValue i LabelValue , które zapewniają funkcje podobne do Pair , ale różnią się semantyką.
Zgodnie z oficjalną witryną wszystkie klasy w javatuples są bezpieczne i niezmienne . Każda klasa krotki implementuje interfejs Iterable , Serializable i Comparable .
3. Dodawanie zależności Mavena
Dodajmy zależność Maven do naszego pom.xml :
org.javatuples javatuples 1.2
Sprawdź repozytorium Central Maven, aby uzyskać najnowszą wersję.
4. Tworzenie krotek
Tworzenie krotki jest naprawdę proste. Możemy użyć odpowiednich konstruktorów:
Pair pair = new Pair("A pair", 55);
Istnieje również trochę mniej rozwlekły i semantycznie elegancki sposób tworzenia krotki:
Triplet triplet = Triplet.with("hello", 23, 1.2);
Możemy również tworzyć krotki z iterowalnego :
List listOfNames = Arrays.asList("john", "doe", "anne", "alex"); Quartet quartet = Quartet.fromCollection(collectionOfNames);
Zwróć uwagę, że liczba pozycji w kolekcji powinna odpowiadać typowi krotki, którą chcemy utworzyć . Na przykład nie możemy stworzyć kwintetu przy użyciu powyższej kolekcji, ponieważ wymaga ona dokładnie pięciu elementów. To samo dotyczy każdej innej klasy krotki o wyższym rzędzie niż Quintet .
Możemy jednak utworzyć krotkę niższego rzędu, taką jak Pair lub Triplet, używając powyższej kolekcji, określając indeks początkowy w metodzie fromIterable () :
Pair pairFromList = Pair.fromIterable(listOfNames, 2);
Powyższy kod spowoduje utworzenie pary zawierającej „ anne ” i „ alex ”.
Krotki można również w wygodny sposób tworzyć z dowolnej tablicy:
String[] names = new String[] {"john", "doe", "anne"}; Triplet triplet2 = Triplet.fromArray(names);
5. Pobieranie wartości z krotek
Każda klasa w javatuples ma metodę getValueX () do pobierania wartości z krotek, gdzie X określa kolejność elementu wewnątrz krotki. Podobnie jak indeksy w tablicach, wartość X zaczyna się od zera.
Stwórzmy nowy kwartet i pobierzmy kilka wartości:
Quartet quartet = Quartet.with("john", 72.5, 32, "1051 SW"); String name = quartet.getValue0(); Integer age = quartet.getValue2(); assertThat(name).isEqualTo("john"); assertThat(age).isEqualTo(32);
Jak widać, pozycja „ jan ” to zero, „ 72,5 ” to jeden i tak dalej.
Zauważ, że metody getValueX () są bezpieczne dla typów. Oznacza to, że nie jest wymagane rzucanie.
Alternatywą jest metoda getValue (int pos) . Pobiera pozycję elementu do pobrania od zera. Ta metoda nie jest bezpieczna dla typów i wymaga jawnego rzutowania :
Quartet quartet = Quartet.with("john", 72.5, 32, "1051 SW"); String name = (String) quartet.getValue(0); Integer age = (Integer) quartet.getValue(2); assertThat(name).isEqualTo("john"); assertThat(age).isEqualTo(32);
Zwróć uwagę, że klasy KeyValue i LabelValue mają odpowiednie metody getKey () / getValue () i getLabel () / getValue () .
6. Ustawianie wartości na krotki
Podobnie jak getValueX () , wszystkie klasy w javatuples mają metody setAtX () . Ponownie, X jest pozycjami od zera dla elementu, który chcemy ustawić:
Pair john = Pair.with("john", 32); Pair alex = john.setAt0("alex"); assertThat(john.toString()).isNotEqualTo(alex.toString());
Ważną rzeczą jest to, że typem zwracanym przez metodę setAtX () jest sam typ krotki. Dzieje się tak, ponieważ javatuples są niezmienne . Ustawienie jakiejkolwiek nowej wartości pozostawi oryginalne wystąpienie nienaruszone.
7. Dodawanie i usuwanie elementów z krotek
Do krotek możemy wygodnie dodawać nowe elementy. Jednak spowoduje to utworzenie nowej krotki o jeden rząd wyżej:
Pair pair1 = Pair.with("john", 32); Triplet triplet1 = pair1.add("1051 SW"); assertThat(triplet1.contains("john")); assertThat(triplet1.contains(32)); assertThat(triplet1.contains("1051 SW"));
Z powyższego przykładu jasno wynika, że dodanie jednego elementu do pary utworzy nowy triplet . Podobnie, dodanie jednego elementu do Tripletu spowoduje utworzenie nowego kwartetu .
The example above also demonstrates the use of contains() method provided by all the classes in javatuples. This is a really handy method for verifying if the tuple contains a given value.
It is also possible to add one tuple to another using the add() method:
Pair pair1 = Pair.with("john", 32); Pair pair2 = Pair.with("alex", 45); Quartet quartet2 = pair1.add(pair2); assertThat(quartet2.containsAll(pair1)); assertThat(quartet2.containsAll(pair2));
Note the use of containsAll() method. It will return true if all the elements of pair1 are present in quartet2.
By default, the add() method adds the element as a last element of the tuple. However, it is possible to add the element at a given position using addAtX() method, where X is the zero-based position where we want to add the element:
Pair pair1 = Pair.with("john", 32); Triplet triplet2 = pair1.addAt1("1051 SW"); assertThat(triplet2.indexOf("john")).isEqualTo(0); assertThat(triplet2.indexOf("1051 SW")).isEqualTo(1); assertThat(triplet2.indexOf(32)).isEqualTo(2);
This example adds the String at position 1, which is then verified by the indexOf() method. Please note the difference in order of the types for the Pair and the Triplet after the call to addAt1() method call.
We can also add multiple elements using any of add() or addAtX() methods:
Pair pair1 = Pair.with("john", 32); Quartet quartet1 = pair1.add("alex", 45); assertThat(quartet1.containsAll("alex", "john", 32, 45));
In order to remove an element from the tuple, we can use the removeFromX() method. Again, X specifies the zero-based position of the element to be removed:
Pair pair1 = Pair.with("john", 32); Unit unit = pair1.removeFrom0(); assertThat(unit.contains(32));
8. Converting Tuples to List/Array
We have already seen how to convert a List to a tuple. Let's now see hot to convert a tuple to a List:
Quartet quartet = Quartet.with("john", 72.5, 32, "1051 SW"); List list = quartet.toList(); assertThat(list.size()).isEqualTo(4);
It is fairly simple. The only thing to note here is that we will always get a List, even if the tuple contains the same type of elements.
Finally, let's convert the tuple to an array:
Quartet quartet = Quartet.with("john", 72.5, 32, "1051 SW"); Object[] array = quartet.toArray(); assertThat(array.length).isEqualTo(4);
Clear enough, the toArray() method always returns an Object[].
9. Conclusion
W tym artykule zbadaliśmy bibliotekę javatuples i zaobserwowaliśmy jej prostotę. Zapewnia elegancką semantykę i jest naprawdę łatwy w użyciu.
Upewnij się, że zapoznałeś się z pełnym kodem źródłowym tego artykułu na GitHub. Kompletny kod źródłowy zawiera trochę więcej przykładów niż te omówione tutaj. Po przeczytaniu tego artykułu dodatkowe przykłady powinny być łatwe do zrozumienia.