mirror of
https://gitlab.com/djdietrick/docs
synced 2026-05-02 22:10:55 -04:00
Started java collections
This commit is contained in:
@@ -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<Card> 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<Card> acesOfHearts = Collections.nCopies(13, aceOfHearts);
|
||||||
|
Card.printDeck(acesOfHearts, "Aces of Hearts", 1);
|
||||||
|
|
||||||
|
Card kingOfClubs = Card.getFaceCard(Card.Suit.CLUB, 'K');
|
||||||
|
List<Card> 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<Card> 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);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user