*JAVA* List method subList(from,to) returns a view of the list ranging from posi
ID: 3711384 • Letter: #
Question
*JAVA*
List method subList(from,to) returns a view of the list ranging from positions from, inclusive, to to, exclusive. Add subList to ArrayList implementation, In the Java library, subList is written in terms of the List interface, but write yours in terms of ArrayList. You will need to define a nested class SubList that extends ArrayList, and have subList return a reference to a new instance of SubList. To keep matters simple, have SubList maintain a reference to the primary ArrayList, store the size of the sublist, and store the offset into the primary ArrayList. You can also have all the mutators in the SubList throw an exception, so the returned sublist is in effect immutable. Your SubList class must itself provide an inner SubListIterator class that implements weiss.util.ListIterator. Test your code on the method in the figure below. Observe that sublists can create sublists, that all refer to smaller portions of the same primary ArrayList.
1 public static Random r-new Random); 2 figure 19.89 Recursion and array sublists. An example for Exercise 19.3 3 public static long sumC ArrayList arr 4 5 f arr.size)0) 6 return 0; 7 else int idx = r.nextInt ( arr.sí ze( ) ); 9 10 return arr.get( idx)+ sumC arr.subList( 0, idx )+ sum( arr.subList( idx + 1, arr.size( ) ) ); 12 13 14 15Explanation / Answer
package net.java.dev.designgridlayout; import java.util.AbstractList; import java.util.List; import java.util.RandomAccess; // Simplified sublist implementation tailored for managing RowItem lists in // SubGrid/GridRow. // This implementation is definitly not complete for external use but perfectly // fulfills its goals in the required context. final class SubList extends AbstractList implements RandomAccess { SubList(List source) { _source = source; _from = source.size(); } @Override public void add(int index, RowItem element) { _source.add(_from + index, element); _size++; } @Override public RowItem get(int index) { return _source.get(_from + index); } @Override public int size() { return _size; } private final List _source; private final int _from; private int _size = 0; }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.