/* * Copyright (c) 2015 Babak Farhang */ import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by babak on 5/2/15. */ public class IR9057625 { /** * Note, there's no recursion in this program, so a StackOverflowError here is * a bug. * * @param args number of iterations */ public static void main(String[] args) { int count; if (args.length > 0) { count = Integer.parseInt(args[0]) + 1; System.out.println("count: " + count); } else { count = 64 * 1024 + 1; System.out.println("count: " + (count - 1) + " (default)"); } List list, original; // this works.. // If I indicated o.w. in my bug report, my bad (!) // // list = new ArrayList<>(count); // for (int i = 0; i < count; ++i) // list.add(i); // this doesn't.. // { Integer[] array = new Integer[count]; for (int i = 0; i < count; ++i) array[i] = i; original = list = Arrays.asList(array); } int iteration = 0; try { for (; list.size() > 1; ) { ++iteration; list = list.subList(1, list.size()); if (!list.get(0).equals(original.get(iteration))) throw new AssertionError(); } Integer testValue = list.get(0); System.out.println("list.get(0): " + testValue); System.out.println("iterations: " + iteration); System.out.println("Hoot! Hoot! Success!"); } catch (StackOverflowError soe) { StackTraceElement[] callStack = soe.getStackTrace(); System.err.println( "StackOverflowError on list.get(0) after " + new DecimalFormat("#,###").format(iteration) + "th iteration of\n" + " list = list.subList(..);\n" + "Thrown at " + callStack[0] + "\n" + "Implementation class: " + list.getClass()); System.exit(1); } // The bug is really in java/util/AbstractList.java: // there the private "SubList" class does not properly override subList(). // Implementations that derive from AbstractList and don't override subList() // inherit this bug. // // For a correct implementation, see how it's done in java/util/ArrayList.java: // there the private SubList class correctly overrides subList (it doesn't layer a // new view on top of the old one). } }