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

I am trying to implement my own sublist method that returns a portion of an arra

ID: 3594755 • Letter: I

Question

I am trying to implement my own sublist method that returns a portion of an array list within it's given parameters. From what I have, my attempt doesnt return multiples elements nor am I sure if I know how. So any help to actually implement the sublist method is appreciative. Note that I do have a variable E[] list as a global variable.

@Override
  
public MyCollection<E> subList(int fromIndex, int toIndex){
if(fromIndex < 0 || toIndex > size)
throw new IndexOutOfBoundsException();
if(fromIndex > toIndex)
throw new IllegalArgumentException();
E[] copyArray;
copyArray = (E[])new Object[toIndex - fromIndex];
int k = 0;
for(int i = fromIndex; i < toIndex; i++){
System.arraycopy(list, i, copyArray, 0, toIndex - fromIndex);
}
return copyArray.forEach
}

Explanation / Answer

public MyCollection<E> subList(int fromIndex, int toIndex){
if(fromIndex < 0 || toIndex >= size)
throw new IndexOutOfBoundsException();
if(fromIndex > toIndex)
throw new IllegalArgumentException();
E[] copyArray;
copyArray = (E[])new Object[toIndex - fromIndex];
int k = 0;
for(int i = fromIndex; i < toIndex; i++){
copyArray[i-fromIndex] = list[i];
}
return copyArray;
}

Here fixed your code

Firstly last element should be exclusive

so condition toIndex >= size

Now in for loop just save value at index to new Array created

and return it.

System.arraycopy method.

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