Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/util/Collections/ReverseOrder.java
38812 views
/*1* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 4593209 800166726* @summary Reverse comparator was subtly broken27* @author Josh bloch28*/2930import java.util.*;31import java.io.*;3233public class ReverseOrder {34static byte[] serialBytes(Object o) {35try {36ByteArrayOutputStream bos = new ByteArrayOutputStream();37ObjectOutputStream oos = new ObjectOutputStream(bos);38oos.writeObject(o);39oos.flush();40oos.close();41return bos.toByteArray();42} catch (Throwable t) {43throw new Error(t);44}45}4647@SuppressWarnings("unchecked")48static <T> T serialClone(T o) {49try {50ObjectInputStream ois = new ObjectInputStream51(new ByteArrayInputStream(serialBytes(o)));52T clone = (T) ois.readObject();53return clone;54} catch (Throwable t) {55throw new Error(t);56}57}5859public static void main(String[] args) throws Exception {60Foo[] a = { new Foo(2), new Foo(3), new Foo(1) };61List list = Arrays.asList(a);62Comparator cmp = Collections.reverseOrder();63Collections.sort(list, cmp);6465Foo[] golden = { new Foo(3), new Foo(2), new Foo(1) };66List goldenList = Arrays.asList(golden);67if (!list.equals(goldenList))68throw new Exception(list.toString());6970Comparator clone = serialClone(cmp);71List list2 = Arrays.asList(a);72Collections.sort(list2, clone);73if (!list2.equals(goldenList))74throw new Exception(list.toString());75}76}7778class Foo implements Comparable {79int val;80Foo(int i) { val = i; }8182public int compareTo(Object o) {83Foo f = (Foo)o;84return (val < f.val ? Integer.MIN_VALUE : (val == f.val ? 0 : 1));85}8687public boolean equals(Object o) {88return o instanceof Foo && ((Foo)o).val == val;89}9091public int hashCode() { return val; }9293public String toString() { return Integer.toString(val); }94}959697