Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a new method named slice(int beginIndex, int endIndex) that returns a new

ID: 3606819 • Letter: W

Question

Write a new method named slice(int beginIndex, int endIndex) that returns a new ArrayList object containing the elements of the calling list between beginIndex (inclusive) and endIndex (exclusive). The calling list should not be modified. This method should throw an IndexOutOfBoundsException if an invalid index is supplied, or if beginIndex is not at least 1 less than endIndex. Example: If list1 is an ArrayList object containing {1, 2, 3, 3, 6, 2, 2, 3, 1, 4}, then calling list1.slice(4,7) should return a new ArrayList object containing the values at indices 4, 5, and 6. The returned list would contain the elements {6, 2, 2}.

Explanation / Answer

==

import java.util.ArrayList;

/**
*
*/

/**
* @author XXXX
*
*/
public class List {

   /**
   *
   */
   java.util.List<Integer> list = new ArrayList<Integer>();

   public java.util.List slice(int beginIndex, int endIndex) {

       if ((beginIndex < 0 && endIndex < 0) || endIndex > list.size() || beginIndex > list.size()
               || beginIndex >= endIndex - 1) {
           throw new IndexOutOfBoundsException();
       }
       int i = 0;
       java.util.List<Integer> list1 = new ArrayList<Integer>();
       for (; beginIndex < endIndex; beginIndex++) {
           list1.add(list.get(beginIndex));
       }
       list = list1;
       return list1;
   }

   /**
   * @param args
   */
   public static void main(String[] args) {

       List list1 = new List();
       list1.add(1);
       list1.add(2);
       list1.add(3);
       list1.add(3);
       list1.add(6);
       list1.add(2);
       list1.add(2);
       list1.add(3);
       list1.add(1);
       list1.add(4);
       System.out.println(list1);
       list1.slice(4, 7);
       System.out.println(list1);
   }

   private void add(int i) {
       // TODO Auto-generated method stub
       list.add(i);
   }

   /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#toString()
   */
   @Override
   public String toString() {
       return list.toString();
   }

}

==

[1, 2, 3, 3, 6, 2, 2, 3, 1, 4]
[6, 2, 2]

==

Thanks

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote