Jake Wharton | 2000b2f | 2019-12-11 20:37:49 -0500 | [diff] [blame] | 1 | // Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file |
| 2 | // for details. All rights reserved. Use of this source code is governed by a |
| 3 | // BSD-style license that can be found in the LICENSE file. |
| 4 | |
| 5 | package backport; |
| 6 | |
| 7 | import java.util.Arrays; |
| 8 | import java.util.HashSet; |
| 9 | import java.util.List; |
| 10 | import java.util.Set; |
| 11 | |
| 12 | public class SetBackportJava10Main { |
| 13 | |
| 14 | public static void main(String[] args) { |
| 15 | testCopyOf(); |
| 16 | } |
| 17 | |
| 18 | private static void testCopyOf() { |
| 19 | Object anObject0 = new Object(); |
| 20 | Object anObject1 = new Object(); |
| 21 | List<Object> original = Arrays.asList(anObject0, anObject1); |
| 22 | Set<Object> copy = Set.copyOf(original); |
| 23 | assertEquals(2, copy.size()); |
| 24 | assertEquals(new HashSet<>(original), copy); |
| 25 | assertTrue(copy.contains(anObject0)); |
| 26 | assertTrue(copy.contains(anObject1)); |
| 27 | assertMutationNotAllowed(copy); |
| 28 | |
| 29 | // Mutate the original backing collection and ensure it's not reflected in copy. |
| 30 | Object newObject = new Object(); |
| 31 | original.set(0, newObject); |
| 32 | assertFalse(copy.contains(newObject)); |
| 33 | |
| 34 | // Ensure duplicates are allowed and are de-duped. |
| 35 | assertEquals(Set.of(1, 2), Set.copyOf(List.of(1, 2, 1, 2))); |
| 36 | |
| 37 | try { |
| 38 | Set.copyOf(null); |
| 39 | throw new AssertionError(); |
| 40 | } catch (NullPointerException expected) { |
| 41 | } |
| 42 | try { |
| 43 | Set.copyOf(Arrays.asList(1, null, 2)); |
| 44 | throw new AssertionError(); |
| 45 | } catch (NullPointerException expected) { |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | private static void assertMutationNotAllowed(Set<Object> ofObject) { |
| 50 | try { |
| 51 | ofObject.add(new Object()); |
| 52 | throw new AssertionError(); |
| 53 | } catch (UnsupportedOperationException expected) { |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | private static void assertTrue(boolean value) { |
| 58 | if (!value) { |
| 59 | throw new AssertionError("Expected <true> but was <false>"); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | private static void assertFalse(boolean value) { |
| 64 | if (value) { |
| 65 | throw new AssertionError("Expected <false> but was <true>"); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | private static void assertEquals(Object expected, Object actual) { |
| 70 | if (expected != actual && !expected.equals(actual)) { |
| 71 | throw new AssertionError("Expected <" + expected + "> but was <" + actual + ">"); |
| 72 | } |
| 73 | } |
| 74 | } |