2

This is a fragment of the overridden method add for ArrayList. My intent is that, to keep the list in alphabetical order(by comparing strings; compareTo is defined in a separate method), it will use compareTo determine what elements should be shifted right until one of the conditions become false(reaching the beginning of the list or finding a string "smaller" than the string arg0), and then insert an arg0. No errors were raised when adding the first element, but a NullPointerException was raised when a second element is added to the ArrayList. How so?

I fixed the NullPointerException problem, but there are still problems within the method.

Given that an array arr[] is already defined(with a length of 20), and arg0 already passed in beforehand:

int instance = this.size();
while(instance > 0 && arg0.compareTo(arr[instance-1]) > 0){
    arr[instance] = arr[instance - 1];
    instance--;
}
arr[instance] = arg0;
return true;
Brynhildr Xie
  • 115
  • 1
  • 3
  • 10

0 Answers0