03-arrayintlist-2

# 03-arrayintlist-2 - CSE143 Lecture3 ArrayIntList...

This preview shows pages 1–8. Sign up to view the full content.

CSE 143 Lecture 3 ArrayIntList slides created by Ethan Apter and Marty Stepp http://www.cs.washington.edu/143/

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 remove ArrayIntList  has an  add , so it should also have a  remove remove  will take an index as a parameter But how do we remove from  ArrayIntList ? Is it enough to just set the value to 0 or -1? No!  0 and -1 can represent real, valid data Instead we need to: shift all remaining valid data, so there is no “hole” in our data decrement size, so there’s one less piece of data
3 Implementing  remove How can we remove an element from the list? list.remove( 2 ); // delete 9 from index 2 index 0 1 2 3 4 5 6 7 8 9 value 3 8 9 7 5 12 0 0 0 0 size 6 index 0 1 2 3 4 5 6 7 8 9 value 3 8 7 5 12 0 0 0 0 0 size 5

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 Implementing  remove , cont. Again, we need to shift elements in the array this time, it's a left-shift in what order should we process the elements? what indexes should we process? list.remove( 2 ); // delete 9 from index 2 index 0 1 2 3 4 5 6 7 8 9 value 3 8 9 7 5 12 0 0 0 0 size 6 index 0 1 2 3 4 5 6 7 8 9 value 3 8 7 5 12 12 0 0 0 0 size 5
5 remove remove  code: public void remove(int index) { for (int i = index; i < size – 1; i++) { elementData[i] = elementData[i + 1]; } size--; } We didn’t “reset” any value to 0.  Why not? Be careful with loop boundaries!

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
6 remove If we made an  ArrayIntList  and  add ed the values 6, 43,  and 97, it would have the following state: 0 1 2 3 4 98 99 elementData: 6 43 97 0 0 . .. 0 0 size: 3 After a call of  remove(0)  it has this state: 0 1 2 3 4 98 99 elementData: 43 97 97 0 0 . .. 0 0 size: 2 We don’t care what values are in the invalid data valid valid invalid invalid
7 Is  ArrayIntList  Finished? What we’ve done so far: Made an  ArrayIntList   class Gave it enough variables to maintain its state Gave it three methods:  add remove , and  toString Sure we could add more methods. .. But what if our client is malicious?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 25

03-arrayintlist-2 - CSE143 Lecture3 ArrayIntList...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online