Presentation is loading. Please wait.

Presentation is loading. Please wait.

19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.

Similar presentations


Presentation on theme: "19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists."— Presentation transcript:

1 19-Mar-16 Collections and ArrayLists.

2 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists. Loading ArrayLists. Some important ArrayList Methods.

3 3 Why Collections? Object-Oriented programs often require defining classes that are collections of objects of another class. Provinces are collections of Counties. Orders are collections of Items. Units are collections of soldiers. Polygons are collections of points. They enable the representation of a one-to-many relationship.

4 4 Collections and Implementations. Collections contain elements. Collections have operations in common but may be implemented differently. Some collections are better for searching and some better for processing elements sequentially. In a production environment, you should choose your collections carefully based on advantages and disadvantages. We will only deal with ArrayLists.

5 5 Collection: Common operations in the Java Collection Library int size( ); boolean isEmpty( ); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator( ); //Traverse the collection.

6 6 Common Operation in a User System Collection Example : Province ….County Possible Methods. addCounty( County county ). Add a county to the collection. removeCounty( County county ). removeCounty( int index ). removeCounty ( String countyName). iterator getCounties(). We need an object which allows us to go through the entire collection of counties. store( String filename). Store contents to named file. load( String filename). Load contents from named file.

7 7 Generics In Java versions 1.4 and earlier, an ArrayList just held Object s, which could be of any (non-primitive) type For compatibility reasons you can still do this, but you will get a lot of warning messages In Java 5 you should specify the class of objects that the ArrayList will hold This is done with the new generics syntax

8 8 Creating a ArrayList the old way The syntax for creating ArrayList s has changed between Java 1.4 and Java 5 For compatibility reasons, the old way still works, but will give you warning messages Here are the (old) constructors: import java.util.ArrayList; //Important ArrayList vec1 = new ArrayList(); Constructs an ArrayList with an initial capacity of 10 ArrayList vec2 = new ArrayList( initialCapacity );

9 9 Using an ArrayList the old way boolean add(Object obj ) Appends the object obj to the end of this ArrayList Example: myArrayList.add("A string is an object"); Object get(int index ) Returns the component at position index Note that this is returned as an Object ; to use it as a String, you must cast it Example: String s = (String)myArrayList.get(5);

10 10 Creating a ArrayList the new way Specify, in angle brackets after the name, the type of object that the class will hold Examples: ArrayList vec1 = new ArrayList (); ArrayList vec2 = new ArrayList (10); To get the old behavior, but without the warning messages, use the wildcard Example: ArrayList vec1 = new ArrayList ();

11 11 Adding elements to a ArrayList boolean add(Object obj ) Appends the object obj to the end of this ArrayList With generics, the obj must be of the correct type, or you get a compile-time (syntax) error Always returns true This is for consistency with other, similar classes void add(int index, Object element ) Inserts the element at position index in this ArrayList The index must be greater than or equal to zero and less than or equal to the number of elements in the ArrayList With generics, the obj must be of the correct type, or you get a compile-time (syntax) error

12 12 Removing elements boolean remove(Object obj ) Removes the first occurrence of obj from this ArrayList Returns true if an element was removed Uses equals to test if it has found the correct element void remove(int index ) Removes the element at position index from this ArrayList void clear() Removes all elements

13 13 Accessing with and without generics Object get(int index ) Returns the component at position index Using get the old way: ArrayList myList = new ArrayList(); myList.add("Some string"); String s = (String)myList.get(0); Using get the new way: ArrayList myList = new ArrayList (); myList.add("Some string"); String s = myList.get(0); Notice that casting is no longer necessary when we retrieve an element from a “genericized” ArrayList

14 14 Searching a ArrayList boolean contains(Object element ) Tests if element is a component of this ArrayList Uses equals to test if it has found the correct element int indexOf(Object element ) Returns the index of the first occurrence of element in this ArrayList Uses equals to test if it has found the correct element Returns -1 if element was not found in this ArrayList int lastIndexOf(Object element ) Returns the index of the last occurrence of element in this ArrayList Uses equals to test if it has found the correct element Returns -1 if element was not found in this ArrayList

15 15 Getting information boolean isEmpty() Returns true if this ArrayList has no elements int size() Returns the number of elements currently in this ArrayList Object[ ] toArray() Returns an array containing all the elements of this ArrayList in the correct order

16 16 More about equals There are many different notions of equality Example: two sets are equal if they contain the same elements; order of elements is irrelevant Java defines public boolean equals(Object) in the Object class, but equals is defined to be the same as == It’s often a good idea to override equals for your own objects If you do this, note that the argument should be a general Object The String class (and some others) override equals

17 17 ArrayList Sample 1 import java.util.*; public class ArrayListGenericDemo { public static void main(String[] args) { ArrayList data = new ArrayList (); data.add("hello"); data.add("goodbye"); // data.add(new Date()); This won't compile! Iterator it = data.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } } }

18 18 Your turn. Write a program that declares a ArrayList of strings and do the following: Load the ArrayList with the strings; “Toronto”, “Montreal”, “Vancouver”, “Frankfurt”. Search for the string “Frankfurt” and print an appropriate message. Remove the city, “Frankfurt” then search for “Frankfurt” again and print an appropriate message.

19 19 Iterating through an ArrayList Use an iterator: Use the hasNext() to test for end of list. Use the next() to get and use the object. Use the size() and get() methods to iterate through the ArrayList using a for. Use a for…each.

20 20 iterators import java.util.*; ArrayList data = new ArrayList ();. // load with elements. Iterator it = data.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } Get an iterator From ArrayList Loop until hasNext fails Get and use Next element

21 21 Iterating using size() and get() import java.util.*; ArrayList data = new ArrayList ();. // load with elements. for(int i=0; i < data.size(); i++) { String s = data.get( i); System.out.println(s); } size() gives you number of elements in ArrayList Get by index.

22 22 Iterating using a for:each import java.util.*; ArrayList data = new ArrayList ();. // load with elements. for(String element:data ) { System.out.println(element); } Declare a variable of same type as ArrayList elements to represent current element in list Use variable. In processing

23 23 Your Turn! Write a program which will create an ArrayList of strings then load it with the strings “L6L1M6”, ”M6N3F5”,”L6K6T2”,”V7TL5T”,”V7TL5T”, “M4F3T5”. Using an iterator traverse the list and remove any string representing a Vancouver postal code (begins with V). After processing the ArrayList in this manner, use a for..each to display the contents of the ArrayList using System.out.println();


Download ppt "19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists."

Similar presentations


Ads by Google