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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.