Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 15: Class.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Chapter 19 Java Data Structures
Java's Collection Framework
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Lists and the Collection Interface Review inheritance & collections.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
CSC 142 P 1 CSC 142 Collections [Reading: Chapter 10]
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 8: Accumulating.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Fall 2013.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
List data type(ADT). Lists Elements : a 1,a 2,a 3,… a i-1,a i, a i+1,…a n Null List contains: 0 elements Types of Operations on list 1.Insertion 2.Deletion.
CS-2852 Data Structures LECTURE 2 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Collections Dwight Deugo Nesa Matic
Object Oriented Programming in Java Habib Rostami Lecture 7.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
The AP Java Subset Topics. A Topics Primitive Types int double boolean.
1 CS162: Introduction to Computer Science II Abstract Data Types.
Java Collections CHAPTER 3-February-2003
Fundamental of Java Programming
Sixth Lecture ArrayList Abstract Class and Interface
Introduction to Collections
Programming in Java Lecture 11: ArrayList
Introduction to Collections
Part of the Collections Framework
Introduction to Collections
Collections Framework
Introduction to Collections
Hashing in java.util
Presentation transcript:

Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 15: Class properties, access rights and Collections Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Structure of this lecture Class properties Access privileges Collections (Arrays and collection types) 2

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties Some properties should be shared by all instances of a class: – A counter stores how many instances of a class were created – The next unique identification for an instance (e.g., customer number) – Constants which may be useful to all objects Class attributes and class methods are features associated with the class itself (not its objects) 3

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties Class features are declared with the keyword static Access with. –Within the class, one may omit the class name They may be accessed from anywhere the class is visible Known examples –Class attribute: System.out –Class method: public static void main(...) 4

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties 5 class Person { static int personCount = 0; Person(.. ) { personCount++; //... } //... initialization occurs before any method is executed static variable only exists once for all objects Upon creation of a new person, the counter is updated

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties // class Person (continued) //... static int personCount() { return personCount; } //... 6 Retrieve the number of existing person objects

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties Access via class name int count = Person.personCount(); System.out.println(count +" objects"); Another typical application boolean isLargerThan(Circle b) {.. } static boolean isLargerThan(Circle a, Circle b) {..} 7 compares two circles receiver compared with another circle object

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties Class methods may not access instance features 8 class Mistake { int i; static void main() { something(i); // … } Not possible unless an object is created or "i" is a class variable Not possible unless an object is created or "i" is a class variable

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties Static Initialization ::= static { } Purpose: initialization of class attributes Similar to constructors for objects Useful if simple initialization is insufficient 9

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class Properties execution upon loading the class definition 10 public class InitializationExample { private static double[] vector = new double[6]; // static initialization block static { for (int i = 0; i < vector.length; i++) { vector[i] = 1.0 / (i + 1); } //... } public class InitializationExample { private static double[] vector = new double[6]; // static initialization block static { for (int i = 0; i < vector.length; i++) { vector[i] = 1.0 / (i + 1); } //... } Static Initialization

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Constants May only receive a value once –after that, read access only => immutable Constants are declared like variables but using the keyword final –private final int MAXIMUM_NUMBER_CARDS = 5; –A constant declaration must always have an initialization part –Convention: capital letters using underscores to separate words 11

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Structure of this lecture Class properties Access privileges Collections (Arrays and collection types) 12

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges Features are declared with their intended visibility – ::= private | ε | protected | public –with the help of visibility modifiers one can determine which clients may access an attribute, method or class Four levels of visibility –hidden elements( private ) –package elements (no modifier) –internal elements ( protected ) –freely accessible elements ( public ) 13

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges private Access possible only from within the class itself 14 package (implicit; no modifier given) The class element is visible for all classes in the same package No access from outside the package is allowed Not even from heirs in another package!  Package as a collection of classes which “trust" each other, have high cohesion

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges protected All classes in the same package may access the element Same for all heirs of the class (even if in a different package)  Heirs as "trusted" clients are allowed to access implementation details of the ancestor 15 public Any class may access the element

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges 16 Same class public protected package private Classes in other packages Heirs in other packages Same package Heirs in same package Overview Have the same access rights

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges 17 package A; public class AA { public int one; protected int two; void three() { … } private void four() { … } } package A; public class AA { public int one; protected int two; void three() { … } private void four() { … } } package B; class BA extends AA { // one, two } package B; class BA extends AA { // one, two } package A; class AB { // one, two, three } package A; class AB { // one, two, three } package B; class BB { // one } package B; class BB { // one } package A; class AC extends AA { // one, two, three } package A; class AC extends AA { // one, two, three }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges Class Modifiers Either public –Unique—worldwide –Only one class may be specified public per file –Filename must be ClassName + “.java” or implicit (no keyword given) –Only visible within the same package 18

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges Modifiers and Redefinition If a method is redefined, its visibility may only be extended Reason: substitutability –It must be possible to substitute an object of a more special type for an object of a more general type –The subclass must offer at least as many features as its ancestor  It must not hide redefined features from clients 19

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Access Privileges Visibility using UML UML offers "public", "protected" and "private" public  + protected  # private  - no modifier  visibility is undefined 20 Class -privateAttribute : AnotherClass #protectedAttribute : int +publicMethod(x: int) : boolean

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Structure of this lecture Class properties Access privileges Collections (Arrays and collection types) 21

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collection Types A frequently needed kind of data structure is a collection for storing multiple data items –either of exactly the same type –or of the same type (including subtypes) –or of various types (i.e., of type Object) Depending on intended use, the collections types… –support quick access to individual elements –provide support for keeping elements sorted –provide a discipline for accessing certain elements only –may grow on demand –etc. 22

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Wrapper Classes Primitive data types are not reference types  Are not derived from Object, can not respond to messages  Can not be assigned to variables of type Object Sometimes it is useful (e.g., for collections) to treat a primitive piece of data as if it were an object  Wrapper Classes 23 Values versus References

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Wrapper Classes Class name is derived from primitive data type, using a capital first letter –java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, java.lang.Character Wrapper objects are immutable –Value assignment happens via constructor –Value inquiry uses a message Value() 24

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Autoboxing - Autounboxing Since Java 1.5, an implicit conversion from int to Integer is possible (same for other types) // AUTOBOXING Integer a = 5; // AUTO-UNBOXING int i = a; 25 Integer a = new Integer(5); int i = a.intValue();

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections Java offers a number of collection types, implementing the java.util.Collection interface, or one of the following sub- interfaces thereof (this list is incomplete!): Collection –A general interface for collections of objects –No restrictions/guarantees regarding duplicates/ordering/sorting, etc. List (has implementations ArrayList, LinkedList, Vector ) –Objects are ordered –May contain duplicates –Enables direct access to objects via an index Set (has implementation HashSet ) –Objects may be contained only once SortedSet (has implementation TreeSet ) –Same as Set but ordered, user may specify custom comparison strategy for elements 26 Collection SortedSet Set List

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Lists In the following, we will assume the use of a collection of type „E“ (for element); this type can be replaced by „appropriate“ types. –Details follow in the slide set about Generics The interface java.util.List contains these methods: –boolean add(E e) Appends element e to the list –void add(int pos, E e) Adds element e to the list at position pos; moves all succeeding elements back by one position –boolean addAll(Collection c) Appends all elements stored in collection c to the list –boolean addAll(int pos, Collection c) Adds all elements of collection c to list, starting at position pos 27

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Lists void clear() –Removes all elements from the list boolean contains(Object o) –Returns true if object o is contained in the list boolean containsAll(Collection c) –Returns true if all objects contained in c belong to the list E get(int pos) –Returns the element at position pos int indexOf(Object o) –Returns the first position at which o occurs in the list, else -1. For the last position, use int lastIndexOf(Object o) boolean isEmpty() –Returns true if the list is empty 28

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Lists E remove(int pos) –Removes the element at position pos and returns it boolean remove(Object O) –Tries to remove object o from the list; returns true if successful int size() –Returns the number of elements stored in the list Object[] toArray() –Returns an array containing all elements of the list Constructors in the subclasses: –Parameterless –With a Collections as a parameter: copies all values into the list –Special cases (see the subtypes) 29

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Implementations of List java.util.LinkedList –Adds the following methods (this is only a subset!): void addFirst(E) void addLast(E) E getFirst() E getLast() java.util.ArrayList –Elements are stored in an array –New methods (selection): void ensureCapacity(int minCapacity) – if the list can contain less than minCapacity elements, the array is adapted to grow void trimToSize() – shrinks the array to the list size –New constructor: ArrayList(int initialCapacity) for the size 30

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Implementations of List java.util.Vector: –Essentially identical to java.util.ArrayList (  array-based) –Accesses are synchronized Avoids problems if two objects want to write or read/write at the same time –„Standard class“ for many applications –Constructors: Vector() – creates a Vector of a default size Vector(int c) – creates a Vector of size c Vector(int c, int inc) – creates a Vector of size c; if this is not enough, the Vector will grow by “inc” elements each time The last constructor is to be preferred –You should determine beforehand how many elements you expect! 31

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Set A Set represents a mathematical set –Thus, a given object can be contained at most once Also supports most of the methods we already know –boolean add(E e) –boolean addAll(Collection c) –void clear() –boolean contains(Object O) –boolean containsAll(Collection c) –boolean isEmpty() –boolean remove(Object O) –boolean removeAll(Collection c) –int size() –Object[] toArray() Insertion fails if the set already contains the object 32

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collections: Set Concrete instances of Set: –java.util.HashSet: stores the data in a hash table (very efficient access) –java.util.TreeSet: stores the data in a tree with an access time of O(log n). There are additional specialized implementations –Please check the JDK API Documentation! 33

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Interface Map Sometimes objects should not be accessible via a numeric index, but via a key (some unique, but otherwise arbitrary value) of some sort, e.g., access telephone number via "surname + name" This is supported by the interface java.util.Map … and its sub-interface SortedMap 34 Map SortedMap

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class: java.util.Hashtable implements java.util.Map Enables access to elements via a computed key, e.g., "surname + name“ Key is first converted into a numeric index and then used for efficient access –Very efficient access –Theory of hashing in ICS II Useful constructors –HashMap() default constructor –HashMap(int size) creates a HashMap of size size –HashMap(Map t) creates a HashMap, containing all elements contained in the map referenced by "t" 35

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Class java.util.Hashtable Useful methods include –Object put(Object key, Object value) stores "value" for retrieval with "key" –Object get(Object key) retrieves object stored with "key" –boolean containsKey(Object key) answers whether an object is stored with "key" –boolean containsValue(Object value) answers whether "value" is stored in the table –Object remove(Object key) removes "key" and the object associated with it 36

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Iterators Java uses an Iterator to step through the elements in a collection Usually, you get the iterator by calling iterator() on the collection –This is true for all subclasses of the Collection interface –For a HashMap, retrieve the keys() first and then use iterator() iterator() returns an instance of java.util.Iterator 37

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Iterators The Iterator type offers only three operations: –boolean hasNext() – are there more elements? –Object next() – returns the next element, if there is one Otherwise, a NoSuchElementException is thrown (see T18) You should check first by using hasNext() –void remove() – removes the last retrieved element May not be supported by all implementing types In this case, you get a UnsupportedOperationException 38

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Iterators Here is a practical example for using Iterators: There is also a variant of the for loop for this purpose: The loop uses an iterator to retrieve next() –This value is then assigned to o in each iteration Usable for iterable elements – most collections, arrays 39 List intList = Arrays.asList(1, 2, 3); // create list int s = 0; for (Iterator it = intList.iterator(); // get Iterator it.hasNext(); ) // continue while elements exist s += (Integer)it.next(); // add next element to sum for (Object o : intList) // get Iterator // continue while elements exist s += (Integer)o; // add next element to sum

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T15 Collection Framework Due to the extent of this subject, and our limited time, we could only partially cover it Find out more on collections at Several specialized classes are available Before implementing a type yourself, check