diff --git a/docs/java/basics/collections.md b/docs/java/basics/collections.md index e69de29..32c5275 100644 --- a/docs/java/basics/collections.md +++ b/docs/java/basics/collections.md @@ -0,0 +1,51 @@ +# Collections + +Java has a class called `java.util.Collections` that defines all of the built in data types, but also provides some helper methods. + +## Helper Methods + +```java +public static void main() { + Card[] cardArray = new Card[13]; + Card aceOfHearts = Card.getFaceCard(Card.Suit.HEART, 'A'); + Arrays.fill(cardArray, aceOfHearts); + Card.printDeck(Arrays.asList(cardArray), "Aces of Hearts", 1); + + List cards = new ArrayList<>(52); + // doesn't add any cards because capacity is 52 but size is 0 + Collections.fill(cards, aceOfHearts); + System.out.println(cards); + System.out.println("cards.size() = " + cards.size()); + + // Returns a list with n copies + List acesOfHearts = Collections.nCopies(13, aceOfHearts); + Card.printDeck(acesOfHearts, "Aces of Hearts", 1); + + Card kingOfClubs = Card.getFaceCard(Card.Suit.CLUB, 'K'); + List kingsOfClubs = Collections.nCopies(13, kingOfClubs); + Card.printDeck(kingsOfClubs, "Kings of Clubs", 1); + + // adds elements to empty lists + Collections.addAll(cards, cardArray); + Collections.addAll(cards, cardArray); + Card.printDeck(cards, "Card Collection with Aces added", 2); + + // copyies over elements at the same index + // in this example we have 26 cards already, so only the first 13 get overwritten + Collections.copy(cards, kingsOfClubs); + Card.printDeck(cards, "Card Collection with Kings copied", 2); + + Collections.shuffle(cards); + Collections.reverse(cards); + + var sortingAlgorithm = Comparator.comparing(Card::rank) + .thenComparing(Card::suit); + Collections.sort(cards, sortingAlgorithm); + + List subList = new ArrayList<>(cards.subList(0,4)); + int subListIndex = Collections.indexOfSubList(cards, subList); + + // Returns true if no elements in second list are found in first list + boolean disjoint = Collections.disjoint(cards, subList); +} +```