List objects; // without type, old!
List<String> strings; // with type String
Collection
Co jsou kontejnery, kolekce (collections)?
Proč je používat?
Kvalitní seznámení s kontejnery najdete na stránkach Oracle |
Základní kategorie jsou dány tím, které rozhraní daný kontejner implementuje:
Vlastní implementace se dá vytvořit implementováním zmíněných rozhraní. |
Set<Person>
)List objects; // without type, old!
List<String> strings; // with type String
Kontejnery bez typů nepoužívat! (Vždy používejte špičaté závorky.) |
Třídy jsou součástí Java Core API (balík java.util
).
Collection
Mezi třídy typu rozhraní
Collection
patří:
List, Set,
… (ne však Map
!)ArrayList, LinkedList, HashSet,
…List<String> listOfStrings = new ArrayList<>();
Collection<String> collection = new HashSet<>();
List<String> listWithValues = List.of("so", "cool");
Collection
IKolekce prvků typu E (tj. Collection<E>
) má následující metody:
boolean add(E e)
e
do kolekcetrue
jestli se skutečne přidal (využití u množin)
int size()
boolean isEmpty()
true
jestli je kolekce prázdná (velikost je 0)Collection
ICollection<String> set = new HashSet<>();
set.add("Pacman"); // true
set.add("Pacman"); // false
set.toString(); // ["Pacman"]
set.size(); // 1
set.isEmpty(); // false
Collection
II
void clear()
boolean contains(Object o)
true
jestli se o
nachází v kolekciequals
boolean remove(Object o)
true
jestli byl prvek odstraněnCollection
IIList<String> list = List.of("Hello", "world");
list.toString(); // ["Hello", "world"]
list.contains("Hello"); // true
list.remove("Hello"); // true
list.toString(); // ["world"]
list.contains("Hello"); // false
list.clear();
list.toString(); // []
Collection
III
Iterator<E> iterator()
T[] toArray(T[] a)
T
Collection<String> c = List.of("a", "b", "c");
String[] stringArray = c.toArray(new String[0]);
// stringArray contains "a", "b", "c" elements
Collection
IV
boolean containsAll(Collection<?> c)
true
jestli kolekce obsahuje všechny prvky z c
Metody vracející true
, když byla kolekce změněna:
boolean addAll(Collection<E> c)
c
boolean removeAll(Collection<?> c)
this - c
)
boolean retainAll(Collection<?> c)
Výraz Collection<?> reprezentuje kolekci jakéhokoliv typu.
|
Collection
IVCollection<String> c1 = List.of("A", "A", "B");
Collection<String> c2 = Set.of("A", "B", "C");
c1.containsAll(c2); // false
c2.containsAll(c1); // true
c1.retainAll(c2); // true
// c1 ["A", "B"]
c1.removeAll(c2); // true
// c1 []
c1.addAll(c2); // true
// c1 ["A", "B", "C"]
/