03-arraylist2-oop - CSE 143 Lecture 3 More ArrayList...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
CSE 143 Lecture 3 More ArrayList ; object-oriented programming reading: 10.1; 8.1 - 8.7 slides created by Marty Stepp http://www.cs.washington.edu/143/
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 Out-of-bounds • Legal indexes are between 0 and the list's size() - 1 . – Reading or writing any index outside this range will cause an IndexOutOfBoundsException . ArrayList<String> names = new ArrayList<String>(); names.add("Marty"); names.add("Kevin"); names.add("Vicki"); names.add("Larry"); System.out.println(names.get(0)); // okay System.out.println(names.get(3)); // okay System.out.println(names.get(-1)); // exception names.add(9, "Aimee"); // exception index 0 1 2 3 value Marty Kevin Vicki Larry
Background image of page 2
3 ArrayList "mystery" ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 10; i++) { list.add(10 * i); // [10, 20, 30, 40, . .., 100] } • What is the output of the following code? for (int i = 0; i < list.size(); i++) { list.remove(i); } System.out.println(list); •Answer: [20, 40, 60, 80, 100]
Background image of page 3

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

View Full DocumentRight Arrow Icon
4 ArrayList "mystery" 2 ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 5; i++) { list.add(2 * i); // [2, 4, 6, 8, 10] } • What is the output of the following code? int size = list.size(); for (int i = 0; i < size; i++) { list.add(i, 42); // add 42 at index i } System.out.println(list); •Answer: [42, 42, 42, 42, 42, 2, 4, 6, 8, 10]
Background image of page 4
5 ArrayList as parameter public static void name ( ArrayList< Type > name ) { •Examp le: // Removes all plural words from the given list. public static void removePlural( ArrayList<String> list ) { for (int i = 0; i < list.size(); i++) { String str = list.get(i); if (str.endsWith("s")) { list.remove(i); i--; } } } • You can also return a list: public static ArrayList< Type > methodName ( params
Background image of page 5

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

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/04/2011 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

Page1 / 19

03-arraylist2-oop - CSE 143 Lecture 3 More ArrayList...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online