Tha Java Programming Language

Size: px
Start display at page:

Download "Tha Java Programming Language"

Transcription

1 Tha Java Programming Language Kozsik Tamás ( ) to/

2 III. Arrays, collections and other baseclasses

3 Some of the baseclasses Object String StringBuffer Integer, Double,... System Math

4 Object The superclass of every other class. (Default, in case of no extends.) Thus every object belongs to the Object class. Defines basic procedures which every object shuld have. String tostring() boolean equals( Object o ) converts to string compares others: clone, getclass, hashcode, finalize, etc.

5 tostring Works for any objects: System.out.println( "o = " + o ); Because of the + sign, o will automatically be converted into a String, calling the tostring method. Many different classes defines a specialized tostring for converting their own objects into strings. The default function defined in Object writes the name and hashcode of the dynamic type of the object on the screen. (The latter one is a number.)

6 equals vs. == The equality of objects can be examined with the equals method. By default, that is the same as ==. But when are two dates equal? They are equal if they report the same date/time, aren't they? The == tells when two references are equal. (I.e. when two objects are the same.) For example the following will not be true: new Date(1970,4,28) == new Date(1970,4,28) Usually, classes redifine the equals method for defining the equality of two objects. The following can be true: (new Date(1970,4,28)).equals( new Date(1970,4,28) )

7 The equals method of the Date public class Date { int year, month, day; class public boolean equals( Object d ){ if( d instanceof Date ) return year == ((Date)d).year && month == ((Date)d).month && day == ((Date)d).day; else return false; } public int hashcode(){ // this is also necessary return 400*year + 31*month + day; }...

8 Example with dates Date d1 = new Date(2001,1,1); Date d2 = new Date(2001,1,1); Date d3 = new Date(1789,7,14); d1.equals(d2)? d1.equals(d3)? d1 == d2? d1 == d3? (new Object()).equals( new Object() )? new Object() == new Object()?

9 The String class A sequence of Unicode characters String s = "Hello!"; String s = new String("Hello!"); The content of a String object cannot be modified. Instead, a new string has to be created. s = "Hi?"; s = new String("Hello?"); But the language have a lot of constructing, querying and comparing procedures. length, charat, compareto, concat, endswith, replace, substring, trim, valueof, indexof, equalsignorecase, tolowercase,...

10 The StringBuffer class A sequence of Unicode characters Its content can be modified without creating a new object. Has a different representation as the String class, so different procedures can be implemented in it efficiently. append, insert, reverse, setcharat, setlength Procedures not just transform the object, but also return a reference to it. It is good for: StringBuffer b = new StringBuffer("Hello!"); b.append(" Hi!").append(" Salut!").reverse();

11 Wrapper classes There are wrapper classes defined for primitive types: Integer, Byte, Double, Boolean, etc. int i = 42; Integer j = new Integer(i); You can use them when you want to use a primitive type value as an object. For example when you need the tostring... System.out.println(42); The following is needed: new Integer(42).toString() Another important example a bit later...

12 Wrapper classes (2) boolean Boolean byte Byte char Character short Short int Integer long Long float Float double Double Procedures e.g. for the Integer class: static int parseint(string s [, int radix]) Integer( String s ) static String tostring( int i [, int radix]) final static int MIN_VALUE, MAX_VALUE

13 Some other important classes Math Math.PI, Math.E abs(), sqrt(), pow(), log(), min(), floor(), round(), rint(), random(), sin(), asin(), toradians() System in, out, err currenttimemilis(), exit(int), gc() Number Common superclass of the numeric

14 Problem Specification of the Java language does not allow the compilers to create extra objects for Strings with the same values. Test the compiler you use! And what happens in case of two Integer objects?

15 For the String problem: String s = new String("Hello!"); String z = new String("Hello!"); if( s == z )...

16 Arrays For storing several values of the same type Efficient access: indexing Inserting and deleting are time-taking procedures

17 Reviving an old example Declaration of an array type variable int t[]; int[] t;

18 Creating an array Variable declaration will not create the array. Array types are similar to classes. Actually, arrays are objects. int[] t = new int[10]; int t[] = new int[10]; An array type variable is just a reference. int[] s; int x = s[0]; int y = s.length; Wrong! It will not work until an array object is created!

19 Accessing an element of an array Indexed from 0 to length-1. Length is given at creating the array. Length cannot be changed. However, a reference to an array "does not care about" the length of the array. int[] x = new int[5]; x = new int[7]; int y[] = x; Querying length: Array index: args.length args[i] Execution system checks the index

20 Initializing an array double[] t = new double[3]; t[0] = 1.0; t[1] = 2.0; t[2] = 3.0; double[] s = new double[3]; for( int i = 0; i < s.length; i++ ) s[i] = i; double[] v = {1.0, 2.0, 3.0};

21 Array of objects Actually, an array consisting of references. Point[] t; t = new Point[3]; for (int i=0; i<3; i++) t[i] = new Point(i,2); Point[] s = { new Point(1,2), new Point(2,2),

22 Multi-dimensional arrays No such thing in Java. But an array of arrays can be created. int[][] mdt = new int[3][2]; for (int i=0; i<3; i++) for (j=0; j<2; j++) mdt[i][j] = i*j;

23 mdt[1] = new int[4]; mdt[1][0] = 2; mdt[1][1] = 4; mdt[1][2] = 8; "Matrix" of an irregular form int mdt[][]; mdt = new int[2][]; mdt[0] = new int[3]; mdt[0][0] = 7; mdt[0][1] = 2; mdt[0][2] = 9;

24 for( int i=0; i<10; i++ ) Heterogenous arrays An array can contain objects of different classes...if they have a common superclass The static types of the elements of an array are the same. The static type determines the procedures that can be used for the elements. The dynamic types of the elements of an array can be different. The dynamic type determines the implementation to be executed. Employee t[] = new Employee[10]; for( int i=0; i<10; i++ ) t[i] = new Employee(); t[42] = new Employer();

25 The array type as a class Similar in many ways... "Subtypes" Object[] t = new Employee[3]; Caution! After this, the following will raise a run-time error: t[0] = new Object();

26 Feladat Define a Matrix type. Procedures: Creating (initializing with zeros or a given element) an Accessing and setting the value of element Multiplication by a scalar Addition Multiplication

27 Other collections sequence set stack heap graph vector list queue tree hashtabl e

28 Efficiency "Trade-off" Array: constant access, linear insert List: linear access, constant insert Heap: logarithmic access and insert Choose the most sufficient for the given problem.

29 Opportunities in Java Arrays Vector, Stack and Hashtable classes from the java.util package parts of the language since JDK 1.0 Collections Framework standard part of the language since JDK 1.2 Other, not standard directories can be also accessed, e.g. JGL.

30 Vector Quite rapid access/insert/deletion first, last, in between Can store Objects boolean contains( Object element ) int indexof( Object element ) Object elementat( int index ) Object lastelement() Object removeelementat(int index) boolean removeelement( Object element ) void insertelementat( Object element, int index ) void addelement( Object element )

31 Example for using a Vector import java.util.*; class ShortWords { public static void main(string args[]){ Vector v = new Vector(); for( int i=0; i<args.length; i++ ){ if( args[i].length() < 10 ){ v.add(args[i]); } } } }

32 Elements of a Vector The type of the elements is Object. Vector lastwithoutwine( Vector v ){ for( int i=0; i<v.size(); i++ ){ String s = (String) v.getelementat(i); if( s.endswith("wine") ) v.removeelementat(i); } return v; }

33 A sequence of numbers If you want to use an array: int[] t = {2,42,37}; new int[3] Integer[] t = { new Integer(2), new Integer(42), new Integer(37) }; Data are stored quite differently in the memory. If you want to use something else, for example Vector: Vector v = new Vector(); v.add( new Integer(42) ); v.add( new Integer(37) );

34 Enumeration Iterator with which an element of a collection can be accessed. For instance a Vector... void writeselement( Enumeration e ){ while( e.hasmoreelements() ){ Object o = e.nextelement(); System.out.println(o); } } writeselement(v.elements())

35 Capacity Any number of elements can be stored in Vector objects. An "array-like" internal representation provides the efficiency of positioning procedures. Sometimes it "becomes full": then it allocates some more memory space to put data in. Increases its capacity automatically. Initial capacity can be set in the constructors. Vector() Vector( int initialcapacity ) Vector( int initialcapacity, int capacityincrement )

36 Problem Write a method which selects the first occurrances of those elements from a vector which occur several times in the vector. Do it in the following way. Querying the Enumeration object, put the elements into another vector one after the other. Before putting one into the other vector, see whether it is in that vector already or not. If yes, put that element into a third vector, too. Then get the elements from that third vector with the help of an Enumeration, and delete the first occurrances of its elements from the first vector.

37 Stack: stack data type A subclass of the Vector. Regular stack procedures: Object push( Object element ) Object pop() Object peek() boolean empty()

38 Hashtable If you do not want to index with numbers, but with other objects... key - value pairs can be stored Hashtable ht = new Hashtable(); ht.put("hat", "red"); ht.put("coat", "blue"); String colorofhat = (String) ht.get("hat"); Search and insert of a pair by its key: Object put( Object key, Object value) Object get( Object key ) Keys and values can be any objects. There can be different keys within a table...

39 More Hashtable procedures searching, deleting, querying keys and values, etc. boolean containskey ( Object key ) boolean containsvalue ( Object value ) Object remove ( Object key ) Enumeration keys() Enumeration elements() int size() void clear() Efficient storage and search by the hashcode() of keys.

40 Example for using a Hashtable Count the occurrance of command-line arguments. java Count go go far away {far=1, go=2, away=1}

41 import java.util.*; class Count { public static void main(string[] args){ Hashtable h = new Hashtable(); for( int i=0; i<args.length; i++ ){ String key = args[i]; Integer number; if( h.containskey(key) ){ number = (Integer) h.get(key); int onemore = number.intvalue() + 1; number = new Integer(oneMore); } else number = new Integer(1); h.put( key, number ); } System.out.println(h); } }

42 Problem Let command-line arguments be numbers. For every different number save its location in the sequence of command-line arguments. If a number occurs more than once, save all its locations. According to this registration, write the numbers and their locations on the screen. java Collect : : 4 1: 2 11: 0 5 {32=[1, 3, 6], 5=[4], 1=[2], 11=[0, 5]}

43 import java.util.*; class Collect { public static void main(string[] args){ Hashtable h = new Hashtable(); for( int i=0; i<args.length; i++ ) putin( h, new Integer(i), new Integer(args[i]) ); writeselement(h); // System.out.println(h); } public static void putin( Hashtable h, Integer pos, Integer number ){...}

44 public static void putin( Hashtable h, Integer pos, Integer number ){ } Vector v; if( h.containskey(number) ) v = (Vector) h.get(number); else v = new Vector(); v.add(pos); h.put( number, v );

45 public static void writeselement( Hashtable h ){ Enumeration numbers = h.keys(); while( numbers.hasmoreelements() ){ Integer number = (Integer) numbers.nextelement(); System.out.print(number + ": "); Vector v = (Vector) h.get(number); Enumeration positions = v.elements(); while( positions.hasmoreelements() ) System.out.print( positions.nextelement() + " " ); System.out.println(); } }

46 Collections Framework A system of Collections, adding abstraction level Interfaces: collection, map, set, list Map Collectio n Set List SortedMap SortedSet

47 Collection: collection boolean add(object o) boolean contains(object o) boolean remove(object o) abstraction boolean addall(collection c) boolean containsall(collection c) boolean removeall(collection c) boolean retainall(collection c) void clear() boolean isempty() int size() Iterator iterator() Object[] toarray()

48 List: a sequence data type the same element can occur several times the order of elements is important two lists are equal if they have the same elements in the same order like Vector, and what is more: Vector implements this interface short procedure names: set, get, add remove removes the first occurrance of an element, add and addall appends it to the end of the list

49 Implementations of List two different implementations linked (list) the LinkedList class efficient insert into the beginning of the list efficient deletion during enumeration vector-like the ArrayList class efficient positioning procedures the generally used one (usually more efficient) Vector is its subclass

50 Example for the List interface import java. util.*; public class insertintolist { public static void main( String[] args) { List s = new ArrayList(); s.add("route"); s.add(new Integer(66)); s.add("route"); s.add("to LA"); System.out.println(s); } } [Route, 66, Route, to LA]

51 Set: set data type each element can occur only once in a set the order of elements is indifferent two sets are equal if they contain the same elements contain: union: intersection: difference: contains, containsall addall retainall removeall Implementation: HashSet Another implementation: TreeSet, which also implements SortedSet thus you can sort the elements of a set

52 An example for the Set interface import java. util.*; public class insertintoset { public static void main( String[] args) { Set s = new HashSet(); s.add("route"); s.add(new Integer(66)); s.add("route"); s.add("to LA"); System.out.println(s); } } [to LA, Route, 66]

53 Iterator: enumerating a collection Like Enumeration interface a bit shorter procedure names you can delete during enumeration Procedures: boolean hasnext(), Object next(), void remove() ListIterator is its subclass. Lists have that iterator. More procedures... boolean hasprevious(), Object previous() void add(object), void set(object) int nextindex(), int previousindex()

54 Example for using an Iterator import java.util.*; public class Iteration { public static void main(string[] args){ Collection c = new ArrayList(); for( int i=0; i<10; i++) c.add( new Double(Math.random()) ); Iterator it = c.iterator(); while( it.hasnext() ){ Double d = (Double) it.next(); if( d.doublevalue() < 0.6 ) it.remove(); } System.out.println(c); } }

55 Map: map data type Like HashTable key - value pairs Iteration on keys: keyset().iterator() on values: values().iterator() on pairs (its name is Entry): entryset().iterator() Two different implementations: HashMap and TreeMap TreeMap implements SortedMap as well (sorted!) We usually use HashMap, because that is more efficient.

56 Sorting Arrays: with the sort method of the Arrays class Lists (List): with the sort method of the Collections class If there is a natural sort defined on the elements of the array/list. (See also the Comparable interface!) int[], Integer[] List in which Double objects will be stored You can also define a new sort. (See also the Comparator interface!)

57 By a natural sort Comparable: int compareto(object o) import java.util.*; class Sort { public static void main( String[] args ) throws ClassCastException { Arrays.sort(args); for( int i=0; i<args.length; i++ ) System.out.println(args[i]); } } Hello java Rendez Hi Hello Salut Hi Salut

58 Problem Let command-line arguments be integers. Sort them and write them on the screen!

59 Defining a new sort Comparator: int compare( Object o1, Object o2 ) class LengthComparator implements Comparator { public int compare(object o1, Object o2) { int h1 = ((String) o1).length(); int h2 = ((String) o2).length(); if( h1<h2 ) return -1; if( h2<h1 ) return 1; return 0; } }

60 import java.util.*; class Sort { public static void main( String[] args ) throws ClassCastException { Arrays.sort(args, new LengthComparator()); for( int i=0; i<args.length; i++ ) System.out.println(args[i]); } } Hi java Rendez Szia Hi Salut Szia

61 List sorting In the same way, with the Collections.sort procedure. It can be either a natural sort or a userdefined one.

62 Other procedures minimum and maximum search max() binary search binarysearch() reverse reverse() fill, copy fill(), copy() shuffle shuffle() min(), Arrays, Collections

63 Problem Give another soultion for sorting numbers: create a Comparator class which compares Strings in the following way: converts them into numbers with the parseint method and then compares those numbers. Solve the sorting of numbers in the following way: instead of putting command-line arguments into an array, put them into an ArrayList object!

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data 1 JAVA PROGRAMMERS GUIDE LESSON 1 File: JGuiGuideL1.doc Date Started: July 10, 2000 Last Update: Jan 2, 2002 Status: proof DICTIONARIES, MAPS AND COLLECTIONS We have classes for Sets, Lists and Maps and

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help Overview Package Class Use Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED FIELD CONSTR METHOD DETAIL: FIELD CONSTR METHOD Página 1 de 30 Java TM 2 Platform

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University C O P Y R I G H T S 2 0 1 5 E O M, H Y E O N S A N G A L L R I G H T S R E S E R V E D - Containers - About Containers

More information

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

The Java Collections Framework and Lists in Java Parts 1 & 2

The Java Collections Framework and Lists in Java Parts 1 & 2 The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering

More information

Class Library java.lang Package. Bok, Jong Soon

Class Library java.lang Package. Bok, Jong Soon Class Library java.lang Package Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr Object class Is the root of the class hierarchy. Every class has Object as a superclass. If no inheritance is specified

More information

Java Collections Framework: Interfaces

Java Collections Framework: Interfaces Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator

More information

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Wrapper classes. Wrapper classes Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

Java Collections. Engi Hafez Seliem

Java Collections. Engi Hafez Seliem Java Collections Engi- 5895 Hafez Seliem Wrapper classes Provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being

More information

Introduction to Collections

Introduction to Collections Module 3 COLLECTIONS Introduction to Collections > A collection sometimes called a container is simply an object that groups multiple elements into a single unit. > Collections are used to store, retrieve,

More information

Sets and Maps. Part of the Collections Framework

Sets and Maps. Part of the 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 int size( ); boolean isempty( ); boolean contains(object

More information

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com 2 Disclaimer & Acknowledgments Even though Sang Shin is a full-time employee

More information

TEXT-BASED APPLICATIONS

TEXT-BASED APPLICATIONS Objectives 9 TEXT-BASED APPLICATIONS Write a program that uses command-line arguments and system properties Write a program that reads from standard input Write a program that can create, read, and write

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description java.lang Interface Iterable Type Parameters: T - the type of elements returned by the iterator Iterator iterator() Returns an iterator over a set of elements of type T. java.util Interface Iterator

More information

Java Collections Framework reloaded

Java Collections Framework reloaded Java Collections Framework reloaded October 1, 2004 Java Collections - 2004-10-01 p. 1/23 Outline Interfaces Implementations Ordering Java 1.5 Java Collections - 2004-10-01 p. 2/23 Components Interfaces:

More information

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1 CS61B Lecture #17 Last modified: Mon Oct 1 13:40:29 2018 CS61B: Lecture #17 1 Topics Overview of standard Java Collections classes Iterators, ListIterators Containers and maps in the abstract Amortized

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

Object-Oriented Programming with Java

Object-Oriented Programming with Java Object-Oriented Programming with Java Recitation No. 2 Oranit Dror The String Class Represents a character string (e.g. "Hi") Explicit constructor: String quote = "Hello World"; string literal All string

More information

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14 MINI-MAX USING TREES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 Spring 2014 2 Important Dates. April 10 --- A4 due (Connect 4, minimax, trees) April 15 --- A5 due (Exercises on different topics,

More information

Collections (Java) Collections Framework

Collections (Java) Collections Framework Collections (Java) https://docs.oracle.com/javase/tutorial/collections/index.html Collection an object that groups multiple elements into a single unit. o store o retrieve o manipulate o communicate o

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5 CSCI 6234 Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship George Blankenship 1 Java Topics Running Java programs Stream I/O New features George Blankenship 2 Running

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures Abstract Data Types (ADTs) Class #08: Linear Data Structures Software Design III (CS 340): M. Allen, 08 Feb. 16 An ADT defines a kind of computational entity: A set of objects, with possible values A set

More information

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList This article discusses the main classes of Java Collection API. The following figure demonstrates the Java Collection framework. Figure

More information

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String. CMSC 131: Chapter 21 (Supplement) Miscellany Miscellany Today we discuss a number of unrelated but useful topics that have just not fit into earlier lectures. These include: StringBuffer: A handy class

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

String. Other languages that implement strings as character arrays

String. Other languages that implement strings as character arrays 1. length() 2. tostring() 3. charat() 4. getchars() 5. getbytes() 6. tochararray() 7. equals() 8. equalsignorecase() 9. regionmatches() 10. startswith() 11. endswith() 12. compareto() 13. indexof() 14.

More information

Object-Oriented Programming

Object-Oriented Programming Data structures Object-Oriented Programming Outline Primitive data types String Math class Array Container classes Readings: HFJ: Ch. 13, 6. GT: Ch. 13, 6. Đại học Công nghệ - ĐHQG HN Data structures 2

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

Interfaces, collections and comparisons

Interfaces, collections and comparisons תכנות מונחה עצמים תרגול מספר 4 Interfaces, collections and comparisons Interfaces Overview Overview O Interface defines behavior. Overview O Interface defines behavior. O The interface includes: O Name

More information

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No

More information

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

Questions and Answers. Q.3) asses is not part of Java's collection framework?explanation:

Questions and Answers.   Q.3) asses is not part of Java's collection framework?explanation: Q.1) $ javac vector.java $ java vector 4 A. [3, 2, 6] B. [3, 2, 8] C. [3, 2, 6, 8] D. [3, 2, 8, 6] ANSWER : [3, 2, 8, 6] $ javac vector.java $ java vector [3, 2, 8, 6] Q.2) Which interface does java.util.hashtable

More information

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started Application Development in JAVA Duration Lecture: Specialization x Hours Core Java (J2SE) & Advance Java (J2EE) Detailed Module Part I: Core Java (J2SE) Getting Started What is Java all about? Features

More information

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Implementations I 1 Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList Stack and queues Array-based implementations

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc. Contents Topic 08 - Collections I. Introduction - Java Collection Hierarchy II. Choosing/using collections III. Collection and Iterator IV. Methods of Collection V. Concrete classes VI. Implementation

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/

More information

STRINGS AND STRINGBUILDERS. Spring 2019

STRINGS AND STRINGBUILDERS. Spring 2019 STRINGS AND STRINGBUILDERS Spring 2019 STRING BASICS In Java, a string is an object. Three important pre-built classes used in string processing: the String class used to create and store immutable strings

More information

Generic Programming. *Really* reusable code

Generic Programming. *Really* reusable code Generic Programming *Really* reusable code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers to create data structures

More information

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know Organizing Data Data Structures that we know 17 Java Collections Generic Types, Iterators, Java Collections, Iterators Today: Arrays Fixed-size sequences Strings Sequences of characters Linked Lists (up

More information

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework Announcements Abstract data types (again) PS 5 ready Tutoring schedule updated with more hours Today s topic: The Java Collections Framework Reading: Section 7.5 An ADT is a model of a collection of data

More information

Programming Techniques

Programming Techniques University of Malta Junior College Department of Computing and Information Technology Programming Techniques IT Advanced Level Course Notes Riccardo Flask 2 Programming Techniques IT Advanced Notes CONTENTS

More information

core programming Basic Java Syntax Marty Hall, Larry Brown:

core programming Basic Java Syntax Marty Hall, Larry Brown: core programming Basic Java Syntax 1 2001-2003 Marty Hall, Larry Brown: http:// Agenda Creating, compiling, and executing simple Java programs Accessing arrays Looping Using if statements Comparing strings

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Up to here Not included in program Java collections framework prebuilt data structures interfaces and methods for manipulating

More information

A simple map: Hashtable

A simple map: Hashtable Using Maps A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put(key, value); To retrieve a value from

More information

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

Ohad Barzilay and Oranit Dror

Ohad Barzilay and Oranit Dror The String Class Represents a character string (e.g. "Hi") Implicit constructor: String quote = "Hello World"; string literal All string literals are String instances Object has a tostring() method More

More information

Generics and collections

Generics and collections Generics From JDK 1.5.0 They are similar to C++ templates They allow to eliminate runtime exceptions related to improper casting (ClassCastException) Traditional approach public class Box { private Object

More information

COMP6700/2140 Abstract Data Types: Queue, Set, Map

COMP6700/2140 Abstract Data Types: Queue, Set, Map COMP6700/2140 Abstract Data Types: Queue, Set, Map Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 19 April 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140

More information

Collections. OOP encapsulates data inside classes, but this doesn t make how you

Collections. OOP encapsulates data inside classes, but this doesn t make how you 2 Collections COLLECTION INTERFACES CONCRETE COLLECTIONS THE COLLECTIONS FRAMEWORK ALGORITHMS LEGACY COLLECTIONS OOP encapsulates data inside classes, but this doesn t make how you organize the data inside

More information

Computer Science II (Spring )

Computer Science II (Spring ) Computer Science II 4003-232-01 (Spring 2007-2008) Week 5: Generics, Java Collection Framework Richard Zanibbi Rochester Institute of Technology Generic Types in Java (Ch. 21 in Liang) What are Generic

More information

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so. CSE 143 Sp04 Midterm 2 Page 1 of 10 Reference information about some standard Java library classes appears on the last pages of the test. You can tear off these pages for easier reference during the exam

More information

EECS 2011 M: Fundamentals of Data Structures

EECS 2011 M: Fundamentals of Data Structures EECS 2011 M: Fundamentals of Data Structures Suprakash Datta Office: LAS 3043 Course page: http://www.eecs.yorku.ca/course/2011m Also on Moodle S. Datta (York Univ.) EECS 2011 W18 1 / 19 Iterators and

More information

Collection Framework Collection, Set, Queue, List, Map 3

Collection Framework Collection, Set, Queue, List, Map 3 Collection Framework Collection, Set, Queue, List, Map 3 1 1. Beginner - What is Collection? What is a Collections Framework? What are the benefits of Java Collections Framework? 3 2. Beginner - What is

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException VERSION A CSC 1351: Final Name: 1 Interfaces, Classes and Inheritance 2 Basic Data Types (arrays, lists, stacks, queues, trees,...) 2.1 Does the following code compile? If it does not, how can it be fixed?

More information

Java 1.8 Programming

Java 1.8 Programming One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Two Running Java in Dos 6 Using the DOS Window 7 DOS Operating System Commands 8 Compiling and Executing

More information

Notes on access restrictions

Notes on access restrictions Notes on access restrictions A source code file MyClass.java is a compilation unit and can contain at most one public class. Furthermore, if there is a public class in that file, it must be called MyClass.

More information

CSE 373. Java Collection Framework. reading: Weiss Ch. 3, 4.8. slides created by Marty Stepp

CSE 373. Java Collection Framework. reading: Weiss Ch. 3, 4.8. slides created by Marty Stepp CSE 373 Java Collection Framework reading: Weiss Ch. 3, 4.8 slides created by Marty Stepp http://www.cs.washington.edu/373/ 1 Arrays array: An object that stores many values of the same type. element:

More information

11. Collections of Objects

11. Collections of Objects 11. Collections of Objects 1 Arrays There are three issues that distinguish arrays from other types of containers: efficiency, type, and the ability to hold primitives. When you re solving a more general

More information

CSC Java Programming, Fall Java Data Types and Control Constructs

CSC Java Programming, Fall Java Data Types and Control Constructs CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference

More information

USAL1J: Java Collections. S. Rosmorduc

USAL1J: Java Collections. S. Rosmorduc USAL1J: Java Collections S. Rosmorduc 1 A simple collection: ArrayList A list, implemented as an Array ArrayList l= new ArrayList() l.add(x): adds x at the end of the list l.add(i,x):

More information

Arrays, Strings and Collections

Arrays, Strings and Collections Arrays Arrays can be informally defined as a group of variables containing values of the same type and that in some way or another they are related. An array has a fixed size that is defined before the

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

Many strategies have been developed for this, but they often produce surprising results.

Many strategies have been developed for this, but they often produce surprising results. Interfaces C++ is among those languages offering multiple inheritance: a class may inherit from more than one direct superclass. This adds flexibility, but it also brings problems. A class may inherit

More information

Framework in Java 5. DAAD project Joint Course on OOP using Java

Framework in Java 5. DAAD project Joint Course on OOP using Java Topic XXX Collections Framework in Java 5 DAAD project Joint Course on OOP using Java Humboldt University Berlin, University of Novi Sad, Polytehnica University of Timisoara, University of Plovdiv, University

More information

Strings and Arrays. Hendrik Speleers

Strings and Arrays. Hendrik Speleers Hendrik Speleers Overview Characters and strings String manipulation Formatting output Arrays One-dimensional Two-dimensional Container classes List: ArrayList and LinkedList Iterating over a list Characters

More information

Java Programming with Eclipse

Java Programming with Eclipse One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Using the Eclipse Software 6 Two Running Java in Eclipse 7 Introduction 8 Using Eclipse 9 Workspace Launcher

More information

Get started with the Java Collections Framework By Dan Becker

Get started with the Java Collections Framework By Dan Becker Get started with the Java Collections Framework By Dan Becker JavaWorld Nov 1, 1998 COMMENTS JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework. "Oh no,"

More information

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

Practical Session 3 Java Collections

Practical Session 3 Java Collections Practical Session 3 Java Collections 1 Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack Maps The Collections class Wrapper classes 2 Collection

More information

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations References: Beginning Java Objects, Jacquie Barker; The Java Programming Language, Ken Arnold and James Gosling; IT350 Internet lectures 9/16/2003 1 Collections Collection types Collection wrappers Composite

More information

MIT AITI Lecture 18 Collections - Part 1

MIT AITI Lecture 18 Collections - Part 1 MIT AITI 2004 - Lecture 18 Collections - Part 1 Collections API The package java.util is often called the "Collections API" Extremely useful classes that you must understand to be a competent Java programmer

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information