Download presentation
Presentation is loading. Please wait.
1
Intro to Collections
2
Array Problems (Immediate)
Must know size Hard to Grow Hard to Shrink Hard to insert in middle Hard to remove from middle Manual search
3
Array Problems (Future)
Assumes Linear Relationship Right and left neighbors
4
Collections Hold a group of things (like a bag)
Expect that all of the things are the same kind of thing (no flour in the sugar bag) Built in: Grow Shrink Insert Remove Search Variety of data structures
5
Collection Problems Additional overhead
Does not quite store primitives Use wrapper classes
6
ArrayList Do not try to use to hold "large" numbers of primatives
Simplest Collection Similar to array (linear) Automatically grows, shrinks, inserts, removes, searches Sort available Do not try to use to hold "large" numbers of primatives
7
ArrayList Must import import java.util.ArrayList; OR
8
Create an ArrayList New operator creates ArrayList object
ArrayList<String> names = new ArrayList<String>(); “Generic” specifies what kind of thing can go in the collection Use generic in declaration and for the new operator (types should match) New operator creates ArrayList object
9
Add item to ArrayList names.add(name); //adds at end
names.add(i, name); //adds in middle names.add(0, name); //adds at beginning
10
Remove item from Array list
names.remove(i); //removes ith item
11
Let’s you use an ArrayList like an array
Get and Set an Item name = names.get(i); names.set(i, “Bruce”); Let’s you use an ArrayList like an array
12
boolean found = names.contain(“Bruce”);
Find an Item boolean found = names.contain(“Bruce”);
13
ArrayList Size int numOfNames = names.size(); Size of Array List
grows and shrinks automatically as items are added and removed
14
Print an ArrayList System.out.println(names);
Handy but may not be the format you want
15
Sort a Collection Collections.sort(names); Note to use sort
items in collection must know how to compare themselves
16
Wrapper Classes Danger!
Each primitive (int, double, boolean, etc.) has a corresponding wrapper class int -> Integer double -> Double boolean -> Boolean Used when Java needs an object Most of the time Java will switch from primitives to wrapper objects “as needed” this is called “autoboxing”. Danger!
17
For Each Another kind of for loop
Visits each item in a collection “in order” Can also be used with array’s for(String name : names) { System.out.println(name); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.