| 7 | |
| 8 | public class ListFeatures { |
| 9 | public static void main(String[] args) { |
| 10 | Random rand = new Random(47); |
| 11 | List<Pet> pets = new PetCreator().list(7); |
| 12 | System.out.println("1: " + pets); |
| 13 | Hamster h = new Hamster(); |
| 14 | pets.add(h); // Automatically resizes |
| 15 | System.out.println("2: " + pets); |
| 16 | System.out.println("3: " + pets.contains(h)); |
| 17 | pets.remove(h); // Remove by object |
| 18 | Pet p = pets.get(2); |
| 19 | System.out.println( |
| 20 | "4: " + p + " " + pets.indexOf(p)); |
| 21 | Pet cymric = new Cymric(); |
| 22 | System.out.println("5: " + pets.indexOf(cymric)); |
| 23 | System.out.println("6: " + pets.remove(cymric)); |
| 24 | // Must be the exact object: |
| 25 | System.out.println("7: " + pets.remove(p)); |
| 26 | System.out.println("8: " + pets); |
| 27 | pets.add(3, new Mouse()); // Insert at an index |
| 28 | System.out.println("9: " + pets); |
| 29 | List<Pet> sub = pets.subList(1, 4); |
| 30 | System.out.println("subList: " + sub); |
| 31 | System.out.println("10: " + pets.containsAll(sub)); |
| 32 | Collections.sort(sub); // In-place sort |
| 33 | System.out.println("sorted subList: " + sub); |
| 34 | // Order is not important in containsAll(): |
| 35 | System.out.println("11: " + pets.containsAll(sub)); |
| 36 | Collections.shuffle(sub, rand); // Mix it up |
| 37 | System.out.println("shuffled subList: " + sub); |
| 38 | System.out.println("12: " + pets.containsAll(sub)); |
| 39 | List<Pet> copy = new ArrayList<>(pets); |
| 40 | sub = Arrays.asList(pets.get(1), pets.get(4)); |
| 41 | System.out.println("sub: " + sub); |
| 42 | copy.retainAll(sub); |
| 43 | System.out.println("13: " + copy); |
| 44 | copy = new ArrayList<>(pets); // Get a fresh copy |
| 45 | copy.remove(2); // Remove by index |
| 46 | System.out.println("14: " + copy); |
| 47 | copy.removeAll(sub); // Only removes exact objects |
| 48 | System.out.println("15: " + copy); |
| 49 | copy.set(1, new Mouse()); // Replace an element |
| 50 | System.out.println("16: " + copy); |
| 51 | copy.addAll(2, sub); // Insert a list in the middle |
| 52 | System.out.println("17: " + copy); |
| 53 | System.out.println("18: " + pets.isEmpty()); |
| 54 | pets.clear(); // Remove all elements |
| 55 | System.out.println("19: " + pets); |
| 56 | System.out.println("20: " + pets.isEmpty()); |
| 57 | pets.addAll(new PetCreator().list(4)); |
| 58 | System.out.println("21: " + pets); |
| 59 | Object[] o = pets.toArray(); |
| 60 | System.out.println("22: " + o[3]); |
| 61 | Pet[] pa = pets.toArray(new Pet[0]); |
| 62 | System.out.println("23: " + pa[3].id()); |
| 63 | } |
| 64 | } |
| 65 | /* Output: |
| 66 | 1: [Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug] |