Lists in Java Part of the Collections Framework









![Object[] to. Array() n n Defined in java. util. Collection interface, so it applies Object[] to. Array() n n Defined in java. util. Collection interface, so it applies](https://slidetodoc.com/presentation_image/842329425cc52c7337dc03fea1b58aef/image-10.jpg)
![<T> T[] to. Array(T[] a) n n n Also defined in java. util. Collection <T> T[] to. Array(T[] a) n n n Also defined in java. util. Collection](https://slidetodoc.com/presentation_image/842329425cc52c7337dc03fea1b58aef/image-11.jpg)














- Slides: 25

Lists in Java Part of the Collections Framework

Kinds of Collections n Collection—a group of objects, called elements n n n Map—a collection that maps keys to values n n Set—An unordered collection with no duplicates n Sorted. Set—An ordered collection with no duplicates List—an ordered collection, duplicates are allowed Sorted. Map—a collection ordered by the keys Note that there are two distinct hierarchies

Using Collections n n import java. util. * or import java. util. Collection; There is a sister class, java. util. Collections; that provides a number of algorithms for use with collections: sort, binary. Search, copy, shuffle, reverse, max, min, etc.

Collections Example import java. util. *; // importing Arrays, List, and Collections public class Test. Collections { public static void main(String args[]) { String[] array = {"Phil", "Mary", "Betty", "bob"}; List<String> my. List = Arrays. as. List(array); Collections. sort(my. List); System. out. println("Sorted: " + my. List); int where = Collections. binary. Search(my. List, "bob"); System. out. println("bob is at " + where); Collections. shuffle(my. List); System. out. println("Shuffled: " + my. List); } } Sorted: [Betty, Mary, Phil, bob] bob is at 3 Shuffled: [Betty, bob, Phil, Mary]

Collections are interfaces n n n Collection is actually an interface Each kind of Collection has one or more implementations You can create new kinds of Collections When you implement an interface, you promise to supply the required methods Some Collection methods are optional n How can an interface declare an optional method?

Creating a Collection n All Collection implementations should have two constructors: n n A no-argument constructor to create an empty collection A constructor with another Collection as argument All the Sun-supplied implementations obey this rule, but— If you implement your own Collection type, this rule cannot be enforced, because an Interface cannot specify constructors

Collection<E>: Basic operations int size( ); boolean is. Empty( ); boolean contains(Object element); boolean add(E element); // Optional boolean remove(Object element); // Optional Iterator<E> iterator( );

Collection: Iterator public interface Iterator<E> { boolean has. Next( ); // true if there is another element E next( ); // returns the next element (advances the iterator) void remove( ); // Optional // removes the element returned by next }

Using an Iterator n n static void print. All (Collection coll) { Iterator iter = coll. iterator( ); while (iter. has. Next( )) { System. out. println(iter. next( ) ); } } has. Next() just checks if there any more elements next() returns the next element and advances in the collection Note that this code is polymorphic—it will work for any collection
![Object to Array n n Defined in java util Collection interface so it applies Object[] to. Array() n n Defined in java. util. Collection interface, so it applies](https://slidetodoc.com/presentation_image/842329425cc52c7337dc03fea1b58aef/image-10.jpg)
Object[] to. Array() n n Defined in java. util. Collection interface, so it applies to all classes that implement Collection Object[ ] to. Array( ) n n Creates a new array of Objects Defined in java. util. Collection interface, so it applies to all classes that implement Collection Example: Object[ ] a = c. to. Array( ); Problem: Returns an array of Objects, so we have to cast every time we want to use something from the array
![T T to ArrayT a n n n Also defined in java util Collection <T> T[] to. Array(T[] a) n n n Also defined in java. util. Collection](https://slidetodoc.com/presentation_image/842329425cc52c7337dc03fea1b58aef/image-11.jpg)
<T> T[] to. Array(T[] a) n n n Also defined in java. util. Collection interface, so it applies to all classes that implement Collection More complex, but definitely worth knowing This version of to. Array: n n n Is a message to some collection of type T objects Takes as parameter an array of some type T Puts the objects from the collection into the array n n n If the array is longer than needed, a null is put in after the data If the array is too short, a new array (of the correct type) is created and returned Examples: Array. List<String> list = new Array. List<String>(); // Put some Strings into list here String[ ] a = new String[20]; list. to. Array(a); String[] b = list. to. Array(new String[0]);

Set operations A B Set union: A B A B Set intersection: A B A B Set difference: A – B

Collection: Bulk operations boolean contains. All(Collection<? > c); boolean add. All(Collection<? extends E c); boolean remove. All(Collection<? > c); boolean retain. All(Collection<? > c); void clear( ); n The last four operations are optional, in order to allow for immutable collections n n That is, they might throw an Unsupported. Operation. Exception add. All, remove. All, retain. All return true if the object receiving the message was modified

Mixing Collection types n Note that most methods, such as boolean contains. All(Collection<? > c); n are defined for any type of Collection, and take any type of Collection as an argument This makes it very easy to work with different types of Collections

singleton n static <T> Set<T>Collections. singleton(T e) returns an immutable set containing only the element e n n This is handy when you have a single element but you would like to use a Set operation c. remove. All(Collections. singleton(e)); will remove all occurrences of e from the Collection c

The List interface n n The order of elements in a List is important, and there may be duplicate elements Operations are exactly those for Collection int size( ); boolean is. Empty( ); boolean contains(Object e); boolean add(E e); boolean remove(Object e); Iterator iterator( ); Object[ ] to. Array( ); <T> T[ ] to. Array(T a[ ]); boolean contains. All(Collection<? > c); boolean add. All(Collection<? extends E> c); boolean remove. All(Collection<? > c); boolean retain. All(Collection<? > c); void clear( );

List implementations n n List is an interface; you can’t say new List ( ) There are two implementations: n n n Linked. List gives faster insertions and deletions Array. List gives faster random access It’s poor style to expose the implementation unnecessarily, so: n Good: List list = new Linked. List ( ); Not as good: Linked. List list = new Linked. List ( );

Inherited List methods n n n list. remove(e) removes the first e add and add. All add to the end of the list To append one list to another: list 1. add. All(list 2); n To append two lists into a new list: List list 3 = new Array. List(list 1); list 3. add. All(list 2); n Again, it's good style to hide the implementation

List: Positional access E get(int index); // Required -- the rest are optional E set(int index, E element); void add(int index, E element); E remove(int index); boolean add. All(int index, Collection<? extends E> c); n These operations are more efficient with the Array. List implementation

List: Searching int index. Of(Object o); int last. Index. Of(Object o); n equals and hash. Code work even if implementations are different

Interface List. Iterator n Iterators specific to Lists: List. Iterator list. Iterator( ); List. Iterator list. Iterator(int index); n n starts at the position indicated (0 is first element) Methods that List. Iterator inherits from Iterator: boolean has. Next( ); E next( ); void remove( ); n Additional methods: boolean has. Previous() E previous()

List: Iterating backwards boolean has. Previous( ); E previous( ); int next. Index( ); int previous. Index( ); n n Think of the iterator as “between” elements Hence, next followed by previous gives you the same element each time

List. Iterator: More operations void add(E o); n n void set(E o); n n Inserts an object at the cursor position // Optional Replaces the current element void remove(int index); // Optional n Removes the last element that was returned by next() or previous()

List: Range-view n List<E> sub. List(int from, int to) allows you to manipulate part of a list n n n Notice the unusual capitalization A sub. List is a “view” into the actual list; manipulating it is manipulating the original list. A sub. List may be used just like any other list n However, it is dangerous to modify the original list and expect the sub. List to remain consistent

The End References: http: //java. sun. com/docs/books/tutorial/collections /interfaces/collection. html http: //java. sun. com/docs/books/tutorial/collections /interfaces/list. html