• No results found

Software Engineering II. Java 2 Collections. Bartosz Walter

N/A
N/A
Protected

Academic year: 2021

Share "Software Engineering II. Java 2 Collections. Bartosz Walter"

Copied!
32
0
0

Loading.... (view fulltext now)

Full text

(1)

Java Java 2 2 Collections Collections

Bartosz Walter

<[email protected]>

Software Engineering II

(2)

Agenda Agenda

1. Basic interfaces: Collection, Set, List, Map 2. Iterators

3. Utility classes for Collections and Arrays 4. Special implementations

5. Comparing objects

(3)

Java

Java 2 2 Collections Collections

(4)

java java . . util util . . Collection Collection

Manages a group of elements

Least common denominator that all collections implement Imposes no constraints on the elements

No direct implementation

General constraints on implementations Two obligatory constructors:

parameterless

Collection()

Collection-based

Collection(Collection)

(5)

java java . . util util . . Collection Collection

Groups of methods:

basic operations – adding, removing, measuring

boolean add(Object)

boolean remove(Object) boolean contains(Object) boolean isEmpty()

Iterator iterator()

bulk operations – operations on groups of elements

boolean addAll(Collection)

boolean removeAll(Collection) boolean containsAll(Object) boolean retainAll()

void clear()

array operations – conversion to arrays

Object[] toArray()

Object[] toArray(Object[])

(6)

Java

Java 2 2 Collections Collections

(7)

java java . . util util .List .List

Subinterface of Collection

Manages a group of ordered elements Puts some constraints on derivatives

Direct implementations:

ArrayList, Vector, LinkedList

General constraints on implementations

Positional Access: manipulate elements based on their numerical position in the list.

Search: search for a specified object in the list and return its numerical position.

List Iteration: extend Iterator semantics to take advantage of the list's sequential nature.

Range-view: perform arbitrary range operations on the list.

(8)

java java . . util util .List .List

Groups of methods:

positional access

Object get(int)

Object set(int, Object) Object add(int, Object) Object remove(int)

search

int indexOf(Object)

int lastIndexOf(Object)

iteration

ListIterator listIterator()

ListIterator listIterator(int)

range view

List subList(int, int)

(9)

Java

Java 2 2 Collections Collections

(10)

java java . . util util .Set .Set

Subinterface of Collection, but no new methods (!) Manages a group of unique elements

Again, puts some constraints on derivatives Direct implementations:

HashSet, TreeSet

Collection collection2 = new HashSet(collection);

public class FindDups {

public static void main(String args[]) { Set s = new HashSet();

for (int i=0; i<args.length; i++) if (!s.add(args[i]))

System.out.println("Duplicate”);

} }

(11)

Java

Java 2 2 Collections Collections

(12)

java java . . util util .Map .Map

Stores pairs, not single objects Maps keys to values

Provides Collection views for keys, values and pairs Cannot contain duplicate keys

Implementations:

HashMap, TreeMap, SortedMap

General constraints on implementations Two obligatory constructors:

parameterless

Map()

Map-based

Map(Map)

(13)

java java . . util util .Map .Map

Groups of methods:

basic operations

Object put(Object, Object) Object get(Object)

Object remove(Object)

boolean containsKey(Object) boolean containsValue(Object) boolean isEmpty()

int size()

bulk operations

void putAll(Map) void clear()

Collection views

Set keySet()

Collection values() Set entrySet()

(14)

Example Example

public class Freq {

private static final Integer ONE = new Integer(1);

public static void main(String args[]) { Map m = new HashMap();

for (int i=0; i<args.length; i++) {

Integer freq = (Integer) m.get(args[i]);

m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1)));

}

System.out.println(m.size()+" distinct words:");

System.out.println(m);

} }

> java Freq if it is to be it is up to me to delegate 8 distinct words:

{to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1}

public class Freq {

private static final Integer ONE = new Integer(1);

public static void main(String args[]) { Map m = new TreeMap();

for (int i=0; i<args.length; i++) {

Integer freq = (Integer) m.get(args[i]);

m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1)));

}

System.out.println(m.size()+" distinct words:");

System.out.println(m);

} }

(15)

Java

Java 2 2 Collections Collections

(16)

java java . . util util . . Iterator Iterator

Generates a serie of elements, one at a time Successive calls return successive elements Replacement for

java.util.Enumeration

No publicly available implementation (!) No public constructor (!)

boolean hasNext() Object next()

void remove()

(17)

Example Example

public class Freq {

public static void main(String args[]) { Collection coll = new ArrayList();

for (int i=0; i<args.length; i++) { coll.add(args[i]);

}

for (Iterator iter = coll.iterator(); iter.hasNext();) String elem = (String) iter.next();

System.out.print(elem + ” ; ”);

} } }

> java Freq if it is to be it is up to me to delegate {if; it; is; be; up; is; me; delegate ...}

(18)

java java . . util util . . ListIterator ListIterator

Subinterface of

java.util.Iterator

Works in either direction

No publicly available implementation (!) No public constructor (!)

void add(Object)

boolean hasPrevious () int nextIndex()

Object previous() int previousIndex() void set(Object)

(19)

Java

Java 2 2 Collections Collections

(20)

Utility classes

Utility classes : : java java . . util util . . Collections Collections

Binary searching for specific object Sorting arbitrary List (*)

Copying Lists

Filling Collections with Objects Finding max and min elements (*) Reversing a List

Shuffling a List

Swapping two elements

(21)

Utility classes

Utility classes : : java java . . util util . . Collections Collections

int binarySearch(List, Object)

int binarySearch(List, Object, Comparator) void copy(List, List)

Void fill(List, Object)

Object max/min(Collection)

Object max/min(Collection, Comparator) List nCopies(int, Object)

void reverse(List) void shuffle(List) void sort(List)

void sort(List, Comparator) void swap(List, int, int)

(22)

Task Task

Suggest an implementation of multibag.

Bag is a map in that each key maps to multiple values.

(23)

Utility classes

Utility classes : : java java . . util util . . Arrays Arrays

Conversion to List

Binary searching for specific object Equality of two arrays

Filling Arrays with Objects Sorting Arrays

List asList(Object[])

int binarySearch(type[], type)

int binarySearch(Object[], Object, Comparator) boolean equals(type[], type[])

void fill(type[], type)

void sort(type[], Comparator)

(24)

Wrapping objects

Wrapping objects : : Immutables Immutables

Make Collection immutable Block any mutating methods

No publicly available implementation (!) No public constructor (!)

Collection unmodifiableCollection(Collection) Set unmodifiableSet(Set)

List unmodifiableList(List) Map unmodifiableMap(Map)

(25)

Wrapping objects

Wrapping objects : : Synchronization Synchronization

Make Collection synchronized Block any mutating methods

No publicly available implementation (!) No public constructor (!)

Collection synchronizedCollection(Collection) Set synchronizedSet(Set)

List synchronizedList(List) Map synchronizedMap(Map)

(26)

Wrapping objects

Wrapping objects : : Singletons Singletons

Return collection of one specific element The collection is immutable

No publicly available implementation (!) No public constructor (!)

Remove all instances of element e

c.removeAll(Collections.singleton(e));

Remove all Lawyers from the map:

profession.values().removeAll(

Collections.singleton(LAWYER));

(27)

Wrapping objects

Wrapping objects : : Empties Empties

Return empty collection

The collection is immutable

Set EMPTY_SET

Collection EMPTY_COLLECTION Map EMPTY_MAP

(28)

Comparing objects

Comparing objects : : java java . . lang lang . . Comparable Comparable

Sorting, searching requires a method of comparing objects Comparison can be extracted and plugged as a parameter Comparable objects can be compared to other objects

Sort a List of people by birthday:

Collections.sort(people);

public class Person implements Comparable { private name, givenName;

// ...

public int compareTo(Object obj) { } public boolean equals(Object obj) { } public int hashCode() {}

}

(29)

Comparing objects

Comparing objects : : java java . . util util . . Comparator Comparator

Sort a List of people by birthday:

Collections.sort(people, comparator);

public class Name implements Comparator {

public int compare (Object obj1, Object obj2) public boolean equals(Object obj)

}

Sorting, searching requires a method of comparing objects

The comparison can be extracted and plugged as a param

Comparators allow for comparing two objects

(30)

Comparing objects

Comparing objects : : java java . . util util . . Comparator Comparator

public class RealComplexComparator implements Comparator {

public int compare (Object obj1, Object obj2) { double re1 = ((Complex) obj1).getReal();

double re2 = ((Complex) obj2).getReal();

return (re1 > re2? 1: (re1 == re2? 0: -1);

} }

(31)

Task Task

Implement sorting a list of Person classes:

using Comparable interface

using Comparators

(32)

Q&A

Q&A

References

Related documents

Object hierarchy Excel object classes are arranged in a hierarchy Application Workbooks collection Workbook Worksheets collection Worksheet Range. Object collections Objects of the

At this stage, the influence of the unbalances and the grounding location in bipolar HVDC grids on fault behavior and protection systems are not fully understood. This paper

When applied to measures with overlap in item content across correlated constructs, in the absence of a global factor and cross-loadings, CFA is forced to account for the shared

Tugas Akhir Pengkajian Seni berjudul: DESKRIPSI PEMASARAN PAMERAN ABSTRACT PARTY BOROBUDUR TODAY 2018 DI GALERI LIMANJAWI ART HOUSE.. Diajukan oleh Alfiyati Baroroh,

2.  TreeSet is constructed using an object implementing the Comparator interface (compare()) to determine the ordering (permits comparing objects of the same or different

Interestingly, she uses more than one colour for Setswana to symbolise different things- both love and calmness and creativity (figure 53). She notes that she has went through a

That null pointer values will take to declare a reference type on data structures and leads to create an instance variable... An object reference obj can be converted to a

public boolean endsWith( String suffix ) public boolean equals( Object anObject ).