3
ArrayList Review Solutions 1.How would you create an array list to store the cities in North Carolina? 2.How would you put “Greensboro” and “Raleigh” into this array list? 3.Suppose the array list is full of cities, but the last city inserted is a duplicate and needs to be removed. How would you remove the last city? ArrayList<String> cities = new ArrayList<String>(); cities.add(“Greensboro”); cities.add(“Raleigh”); cities.remove(cities.size()-1);

ArrayList Review Solutions

Embed Size (px)

DESCRIPTION

ArrayList Review Solutions. How would you create an array list to store the cities in North Carolina? ArrayList cities = new ArrayList(); How would you put “Greensboro” and “Raleigh” into this array list? cities.add(“Greensboro”); cities.add(“Raleigh”); - PowerPoint PPT Presentation

Citation preview

Page 1: ArrayList Review Solutions

ArrayList Review Solutions1. How would you create an array list to store the cities in North

Carolina?

2. How would you put “Greensboro” and “Raleigh” into this array list?

3. Suppose the array list is full of cities, but the last city inserted is a duplicate and needs to be removed. How would you remove the last city?

ArrayList<String> cities = new ArrayList<String>();

cities.add(“Greensboro”); cities.add(“Raleigh”);

cities.remove(cities.size()-1);

Page 2: ArrayList Review Solutions

ArrayList Review Solutions4. “Kernersville” changed its name to “K-Vegas”. Find this element and

change it.

5. You need to start over and get rid of all the cities in the array list. How would you do that?

for (int i=0; i<cities.size(); i++){ if (cities.get(i).equals(“Kernersville”) { cities.set( i,”K-Vegas”); break; }}

cities.clear();

Page 3: ArrayList Review Solutions

ArrayListfrequently used methods

Name Useadd(item) adds item to the end of the list

add(index,item) adds item at index – shifts items up->

set(index,item) replaces item at index (returns old element) (similar to z[index]=item)

get(index) returns the item at index (similar to z[index] )

size() returns the number of items in the list (similar to z.length)

remove(index) removes the item at index (returns element that was removed)

remove(value) removes first item that matches this value (returns true if item was found, else false)

clear() removes all items from the list

import java.util.ArrayList;