Java kalbos naujovės (nenagrinėtos paskaitose: versijos) R.Vaicekauskas. mif.vu

Size: px
Start display at page:

Download "Java kalbos naujovės (nenagrinėtos paskaitose: versijos) R.Vaicekauskas. mif.vu"

Transcription

1 Java kalbos naujovės (nenagrinėtos paskaitose: versijos) R.Vaicekauskas. mif.vu 2016

2 Java nuo 5 versijos (2004 rugs.) kalbinės ypatybės Parametrizuojamieji tipai (generics); for ciklas iteratoriams; neišreikštinė primityviųjų tipų konversiją į objektus ir atvirkščiai(auto boxing, unboxing); vardiniai tipai (enum); metodai su kintamu parametrų skaičiumi (varargs); statinių elementų importas.

3 Generics parametrizuojami tipai Įgalina naudoti tipizuotas kolekcijas. Sumažina klaidų kiekį, kurios atsirastų, vykdant nekontroliuojamą tipų konversiją. Java naudoja C++ pavidalo sintaksę. Javoje tipų kontrolė vykdoma kompiliacijos metu, o gautas (.class) kodas suderinamas su ankstesnėmis java versijomis. Kritika: komplikuota tipų hierarchija, ribotos galimybės, pvz., lyginant su C++ šablonais.

4 Parametr. tipai : pavyzdys // Removes 4-letter words from c. Elements must be strings static void expurgate(collection c) { for (Iterator i = c.iterator(); i.hasnext(); ) if (((String) i.next()).length() == 4) i.remove(); // Generics atvejis static void expurgate ( Collection<String> c) { for (Iterator<String> i = c.iterator(); i.hasnext(); ) if (i.next().length() == 4) i.remove();

5 for ciklas konteinerių peržiūrai void cancelall(collection<timertask> c) { // Senas for (Iterator<TimerTask> i = c.iterator(); i.hasnext(); ) i.next().cancel(); void cancelall(collection<timertask> c) { // Naujas for (TimerTask t : c) t.cancel();

6 for ciklas masyvams // Returns the sum of the elements of a int sum(int[] a) { int result = 0; for (int el : a) result += el; return result;

7 Parametr. tipų apibrėžimas (Pagal: public interface List<E> { void add(e x); Iterator<E> iterator(); // Kita... public interface Iterator<E> { E next(); boolean hasnext(); // Kita

8 Tipų (ne)suderinamumas List<String> ls = new ArrayList<String>(); // Tinka, kadangi ArrayList išvestas iš List List<Object> lo = ls; // Klaida, nes priešingu atveju galiotų: lo.add(new Object()); String s = ls.get(0); // Nesuderinami tipai Pastaba: prisiminkime situaciją su masyvais.

9 Bendrinių tipų (wildcards) naudojimas Bendr. tipų įvedimą iššaukė poreikis turėti supertipą parametrizuotiems tipams Pavyzdys: aprašome funkciją, kuri gebėtų atspausdinti visus kolekcijos elementus. void printcollection( Collection<?> c) { for (Object e : c) { System.out.println(e);

10 Bendriniai tipai (2) Collection<?> - visų kolekcijų supertipas? žymi bet kurį tipą (išvestą iš Object), taigi leistina: Collection<?> c = new ArrayList<String>(); Tačiau: c.add(new Object()); //kompil. klaida

11 Riboti bendriniai tipai (Bounded Wildcards) tai deklaracija, jog (nežinomas) parametrizuotas išvestas iš konkretaus tipo (t.y., įgyvendina tam tikrą sąsają) Pavyzdys, turime klasių hierarchiją. Circle draw() Shape draw() Rectangle draw() Problema. Kaip apibrėžti bendrą tipą visų figūrų kolekcijoms, kad įgalinti braižomumą?

12 Sprendimas public void drawall(list<? extends Shape> shapes) { for (Shape s: shapes) s.draw(); // Panaudojimas List<Circle> lc = new ArrayList<Circle>(); drawall(lc);

13 Kaina, mokama už lankstumą public void addrectangle( List<? extends Shape> shapes) { shapes.add(0, new Rectangle()); // Kompiliavimo klaida!

14 Parametrizuoti metodai - pavyzdys static <T> void fromarraytocollection( T[] a, Collection<T> c) { for (T o : a) { c.add(o); //Tipas T nustatomas kvietimo metu: Object[] oa = new Object[100]; Collection<Object> co = new ArrayList<Object>(); fromarraytocollection(oa, co);// T :Object String[] sa = new String[100]; Collection<String> cs = new ArrayList<String>(); fromarraytocollection(sa, cs);// T : String fromarraytocollection(sa, co);// T : Object

15 Parametrizuotų metodų ir bendrinių tipų bendras naudojimas Įmanomas, pavyzdys: class Collections { public static <T> void copy(list<t> dest, List<? extends T> src){... Įmanoma: class Collections { public static <T, S extends T> void copy(list<t> dest, List<S> src){...

16 Bendriniai riboti iš apačios tipai (1) interface Sink<T> { flush(t t); public static <T> T writeall(collection<t> coll, Sink<T> s) {... T last; for (T t : coll) { last = t; s.flush(last); return last; Sink<Object> s; Collection<String> cs; String str = writeall(cs, s); // Illegal parameters

17 Bendriniai riboti iš apačios tipai (2) public static <T> T writeall (Collection<? extends T>, Sink<T>) { String str = writeall(cs, s); // Wrong return type. public static <T> T writeall(collection<t> coll, Sink<? super T> snk) {... String str = writeall(cs, s); // OK!

18 Diamond (rombo) operacija Supaprastina parametrizuotų tipų apibrėži-mą (nuo java 1.7). Vietoje: Map<String, List<String>> mymap = new HashMap<String, List<String>>(); Map<String, List<String>> mymap = new HashMap<>();

19 Suderinamumas su java v.1.4 Leidžiama naudoti primityviasias neparametrizuotąsias (raw) kolekcijas. Jas reikėtų traktuoti kaip nežinomo tipo (<?>), o kompiliatorius gali generuoti įspėjimus. Bet kuriuo atveju sukompiliuotame kode jokios tipų informacijos nebelieka: List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getclass()); //true

20 Realizacijos ypatybės Visi parametrizuotos klasės panaudojimai vykdymo metu dalijasi vienu klasės egzemplioriumi Todėl nėra prasmės tikrinti ar duotasis objektas yra konkretaus parametrizuoto tipo egzempliorius (instanceof) kompiliatoriaus įspėjimas Negalima naudoti klasės parametrą apibrėžiant statinius elementus, negalima kurti parametro tipo objekto. Yra apribojimų naudojant masyvus class Mylist<T>{ T t1 = new T(); // Draudžiama static T t; // Draudžiama

21 Autoboxing Tai automatinė tipų konversija tarp primityviųjų tipų (int,double,...) ir atitinkamų juos gaubiančiųjų klasių (Integer,Double,... ) Poreikis konteinerių naudojamas skaičiams (primit. tipams) saugoti Įgalina išraiškas žemiau pateiktos išraiškos naudojimą. Reikiamą kodą paruošia kompiliatorius. Integer refinteger = 1;

22 Autoboxing naudojimo pavyzdys import java.util.*; // Prints a frequency table of the words on the command line public class Frequency { public static void main(string[] args) { Map<String, Integer> m = new TreeMap<String, Integer>(); for (String word : args) { Integer freq = m.get(word); m.put(word, (freq == null? 1 : freq + 1)); System.out.println(m); java Frequency if it is to be it is up to me to do the watusi {be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1

23 enum vardinis tipas public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3; enum Season { WINTER, SPRING, SUMMER, FALL // Naujoji versija Iš esmės tai klasė, kurios objektai konstatiniai (vardiniai) elementai. Papildomos galimybės: Season[] vals = Season.values();

24 varargs metodai su kintamu argumentų skaičiumi Pavyzdys: klasės java.util.formatter format() metodas, kuriam paskutinieji parametrai gali būti perduoti kaip masyvas arba tiesiog atskirti kableliais. public static String format (String pattern, Object... args); Ypač paprastas panaudojimas naudojant autoboxing ypatybę. String result =Formatter.format ( %d min iki %s, 5, paskaitos );

25 Lambda išraiškos (1) import java.util.*; import java.util.function.*; public class ForEach { public static void main(string[] args){ List<String> l = Arrays.asList("vienas", "du","trys"); l.foreach( new Consumer<String>(){ public void accept(string s) { System.out.println(s); ); // Lambdas l.foreach( e -> System.out.println( e ) );

26 Lambda išraiškos (2) Arrays.asList( "a", "b", "d" ).foreach( ( String e ) -> System.out.println( e ) ); Arrays.asList("a", "b", "d").foreach( e -> { System.out.print( e ); System.out.print( e ); ); final String separator = ","; Arrays.asList( "a", "b", "d" ).foreach( ( String e ) -> System.out.print( e + separator ) ); Arrays.asList( "a", "b", "d" ).sort( ( e1, e2 ) -> e1.compareto( e2 ) ); Arrays.asList( "a", "b", "d" ).sort( ( e1, e2 ) -> { int result = e1.compareto( e2 ); return result; );

27 Pabaiga

Java Lectures. Enhancements in Java 1.5

Java Lectures. Enhancements in Java 1.5 1 Enhancements in Java 1.5 2 Generics Enhancement to the type system: a type or method can operate on objects of various types with compile-time type safety, compile-time type safety to the Collections

More information

JAVA V Source files Java, winter semester

JAVA V Source files Java, winter semester JAVA Source files 17.10.2017 1 Unicode programs ~ Unicode comments, identifiers, char and string constants the rest is in ASCII (

More information

JAVA V Assertions Java, winter semester

JAVA V Assertions Java, winter semester JAVA Assertions 1 Assertion since Java 1.4 the statement with a boolean expression a developer supposes that the expression is always satisfied (evaluates to true) if it is evaluated to false -> error

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = myintlist.iterator().next(); // 3 3 Example

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = (Integer) myintlist.iterator().next(); // 3

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? 10/26/10 1 Subtyping for behaviour the inner style class Reservation { date... ; customer... ; void print() { // print Date and Customer inner; class FlightReservation extends

More information

Java Generics Java, summer semester

Java Generics Java, summer semester Java Generics Introduction similar to the templates in C#/C++ but only on first view typed arguments goal clear code type safety Motivational example without generics (

More information

Java Generics. Lecture CS1122 Summer 2008

Java Generics.  Lecture CS1122 Summer 2008 Java Generics http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf Lecture 17 -- CS1122 Summer 2008 Java Generics quick review When you see in Java, you are dealing with generics Generics allow

More information

Masyvai Javoje. Masyvai. Objektų talpyklos. Masyvo tipas. Deklaravimo pavyzdžiai. Deklaracija ir sukūrimas. Masyvo superklas - Object

Masyvai Javoje. Masyvai. Objektų talpyklos. Masyvo tipas. Deklaravimo pavyzdžiai. Deklaracija ir sukūrimas. Masyvo superklas - Object Masyvai Javoje Masyvai. Objektų talpyklos (Arrays, collections) Dinamiškai sukuriami java objektai iš anksto apibr žtam komponenčių skaičiui saugoti. Komponent s g.b. primityvaus tipo arba nuorodos tipo

More information

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping Outline 1 2 Outline 1 2 (Parametric) classes are classes that have Parameters A generic class with a concrete type parameter is an instance of the generic class The type parameter can be the type of variables,

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? Reservation date customer print() FlightReservation flight seat print() TrainReservation train waggon seat print() 10/23/2009 1 Subtyping for behaviour the inner style class Reservation

More information

1.1. Annotations History Lesson - C/C++

1.1. Annotations History Lesson - C/C++ 1. Additions Thanks to Dr. James Heliotis. He started it all :) See also here: and see also here: and here: You need to use the tools from the Java release candidate 1 % bash % export PATH=/usr/local/j2sdk1.5.0-rc1/bin:$PATH

More information

#Students per correct answers

#Students per correct answers Generics in Java Programming Projects 14/04/15 1 #Students per correct answers Quiz"2" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" #"Correct"Answers" 10" 9" 8" 7" 6" 5" 4" 3" 2"

More information

CS108, Stanford Handout #8. Java Generics

CS108, Stanford Handout #8. Java Generics CS108, Stanford Handout #8 Fall, 2007-08 Nick Parlante Java Generics Java generics (added in version 5) are a mixed bag. Some uses of generics are simple to understand and make the code cleaner. They are

More information

The collections interfaces

The collections interfaces Generics in Java Advanced Programming 4/18/16 1 The collections interfaces Contains unique elements Maps unique keys to values 4/18/16 2 Collections in Java Array has a special language support Iterators

More information

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Announcements. Java Graphics. Exceptions. Java Odds & Ends Java Odds & Ends Lecture 25 CS211 Fall 2005 Final Exam Wednesday, 12/14 9:00-11:30am Uris Aud Review Session Sunday, 12/11 1:00-2:30pm Kimball B11 Check your final exam schedule! Announcements For exam

More information

Forthcoming Java Programming Language Features. Joshua Bloch and Neal Gafter Senior Staff Engineers Sun Microsystems, Inc.

Forthcoming Java Programming Language Features. Joshua Bloch and Neal Gafter Senior Staff Engineers Sun Microsystems, Inc. Forthcoming Java Programming Language Features Joshua Bloch and Neal Gafter Senior Staff Engineers Sun Microsystems, Inc. A Brief History of the Java Programming Language 1995 (1.0) First public release

More information

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java. JAVA GENERICS Lecture CS110 Fall 018 Photo credit: Andrew Kennedy Java Collections Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob */ boolean

More information

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes Problems Often you need the same behavior for different kind of classes Java Generics Use Object references to accommodate any object type Use Generic classes and Method The use of Object references induces

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 18 21:04:53 2018 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

Photo credit: Andrew Kennedy JAVA GENERICS

Photo credit: Andrew Kennedy JAVA GENERICS Photo credit: Andrew Kennedy JAVA GENERICS Lecture 17 CS2110 Spring 2017 Java Collections 2 Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 19 19:36:29 2017 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

University of Tokyo Java Class September 22-26, 2003 Forthcoming Java Language Features

University of Tokyo Java Class September 22-26, 2003 Forthcoming Java Language Features University of Tokyo Java Class September 22-26, 2003 Forthcoming Java Language Features Marc Hamilton Director of Technology Global Education and Research Sun Microsystems, Inc Watch Out for Tigers! Java

More information

C++ programavimo kalba. Konstruktorius, destruktorius, klasių metodų modifikatoriai, objektų masyvai (4 paskaita)

C++ programavimo kalba. Konstruktorius, destruktorius, klasių metodų modifikatoriai, objektų masyvai (4 paskaita) C++ programavimo kalba Konstruktorius, destruktorius, klasių metodų modifikatoriai, objektų masyvai (4 paskaita) Konstruktorius Sukuriant objektą, jo duomenims paprastai turi būti priskiriamos pradinės

More information

Polimorfizmas. Lekt. dr. Pijus Kasparaitis m. m. pavasario semestras.

Polimorfizmas. Lekt. dr. Pijus Kasparaitis m. m. pavasario semestras. Polimorfizmas Lekt. dr. Pijus Kasparaitis pkasparaitis@yahoo.com 2009-2010 m. m. pavasario semestras Dar apie paveldėjimą Java kalboje kiekvienas paveldėtos klasės objektas gali būti naudojamas ten, kur

More information

PARAMETRIC POLYMORPHISM

PARAMETRIC POLYMORPHISM PARAMETRIC POLYMORPHISM Java C#! Parametric polymorphism: " Java Generics and Generic C# for.net! The idea: the compiler is able to check parametric classes just looking at their definilon 1 Java Generics

More information

Java. Platforms, etc.

Java. Platforms, etc. Java Platforms, etc. Java object oriented (almost) all is object interpreted source code (.java) compiled to the bytecode bytecode (.class) interpreted by the virtual machine platform independent programs

More information

Java. Platforms, etc.

Java. Platforms, etc. Java Platforms, etc. Java object oriented (almost) all is object interpreted source code (.java) compiled to the bytecode bytecode (.class) interpreted by the virtual machine platform independent programs

More information

CMSC 202H. Containers and Iterators

CMSC 202H. Containers and Iterators CMSC 202H Containers and Iterators Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects Arrays are compiler-supported

More information

JAVA pagrindai Lek. Liudas Drejeris

JAVA pagrindai Lek. Liudas Drejeris JAVA pagrindai Lek. Liudas Drejeris Programa (1) Programa, tai eilė instrukcijų (vadinamų programiniais sakiniais), kurie vykdomi paeiliui, kol gaunamas norimas rezultatas. Programa (2) Programa (2) /*

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages! Java Generics II Dr. Hyunyoung Lee!!! 1 Type System and Variance Within the type system of a programming language, variance refers to how subtyping between complex types

More information

Software Engineering. Prof. Agostino Poggi

Software Engineering. Prof. Agostino Poggi Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma Software Engineering Generics Prof. Agostino Poggi public class ListOfIntegers { //... fields...

More information

Topic 5: Enumerated Types and Switch Statements

Topic 5: Enumerated Types and Switch Statements Topic 5: Enumerated Types and Switch Statements Reading: JBD Sections 6.1, 6.2, 3.9 1 What's wrong with this code? if (pressure > 85.0) excesspressure = pressure - 85.0; else safetymargin = 85.0 - pressure;!

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? Reservation date customer FlightReservation flight seat print() print() TrainReservation train waggon seat print() 10/4/2004 1 Subtyping for behaviour BETA style class Reservation

More information

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B:

More information

Java: exceptions and genericity

Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exceptions Exceptions

More information

Gijos. Gijų modelis Javoje. R.Vaicekauskas, OP, 2017

Gijos. Gijų modelis Javoje. R.Vaicekauskas, OP, 2017 Gijos Gijų modelis Javoje R.Vaicekauskas, OP, 2017 1 Turinys Motyvacija Sukūrimas Valdymas Sinchronizacija Susijusios klasės 2 Motyvacija Gijos reikalingos tam, kad išreikšti lygiagretumą vieno proceso

More information

DrStrangebrac<E,T> Or how I learned to stop worrying, and love generics...

DrStrangebrac<E,T> Or how I learned to stop worrying, and love generics... DrStrangebrac Or how I learned to stop worrying, and love generics... a presentation to The Seattle Java Users Group by Wilhelm Fizpatrick http://www.agileinformatics.com/ Java is Sun Microsystems,

More information

INF3110 Programming Languages Object Orientation and Types, part II

INF3110 Programming Languages Object Orientation and Types, part II INF3110 Programming Languages Object Orientation and Types, part II 10/31/17 1 Object Orientation and Types Lecture I Lecture II - Today From predefined (simple) and user-defined (composite) types via

More information

C++ programavimo kalba

C++ programavimo kalba C++ programavimo kalba Šablonai (10 paskaita) Kodėl šablonai (templates)? Programuojant egzistuoja situacijos, kai reikia atlikti tuos pačius veiksmus su skirtingais duomenų tipais (pvz. modulio radimas,

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

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #23 Announcements: Josh s office hours are now back in his office. HW6 now due Saturday. Partial solar eclipse tomorrow, starting at 1:52PM. Next one in August, 2017. See http://www.timeanddate.com/eclipse/list.html

More information

Apletai (įskiepiai) Lekt. dr. Pijus Kasparaitis m. m. pavasario semestras.

Apletai (įskiepiai) Lekt. dr. Pijus Kasparaitis m. m. pavasario semestras. Apletai (įskiepiai) Lekt. dr. Pijus Kasparaitis pkasparaitis@yahoo.com 2008-2009 m. m. pavasario semestras Java grafinės bibliotekos AWT (Abstract Window Toolkit) Swing 2009.04.09 P.Kasparaitis. Objektinis

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

Parengė ITMM Artūras Šakalys 1

Parengė ITMM Artūras Šakalys 1 2014.02.02 Parengė ITMM Artūras Šakalys 1 2014.02.02 Parengė ITMM Artūras Šakalys 2 Kaip suprantame masyvą? Pavyzdys: Peteliškių šeima; Gėlių laukas; 2014.02.02 Parengė ITMM Artūras Šakalys 3 Kaip suprasti

More information

Parametric polymorphism and Generics

Parametric polymorphism and Generics Parametric polymorphism and Generics Today s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping.

More information

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. 1. The Nose class... b) will not compile because the m1 method parameter should be named n, not x. 2. The Ears class...

More information

Enhancing the JR Concurrent Programming Language with New Java 5.0 Features. HIU NING CHAN B.S. (University of California, Davis) 2004 THESIS

Enhancing the JR Concurrent Programming Language with New Java 5.0 Features. HIU NING CHAN B.S. (University of California, Davis) 2004 THESIS Enhancing the JR Concurrent Programming Language with New Java 5.0 Features By HIU NING CHAN B.S. (University of California, Davis) 2004 THESIS Submitted in partial satisfaction of the requirements for

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards

More information

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm CSC 172 Data Structures and Algorithms Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm Agenda Administrative aspects Java Generics Chapter 1 ADMINISTRATIVE ASPECTS Workshops Workshops Workshops begin on this

More information

CSE 331. Generics (Parametric Polymorphism)

CSE 331. Generics (Parametric Polymorphism) CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 Parametric polymorphism

More information

Struktūrų sintaksė Struktūra tai vienodo arba skirtingo tipo kintamųjų rinkinys. Sintaksė: struct vardas { ; type1 var1; type2 var2;... typen varn; //

Struktūrų sintaksė Struktūra tai vienodo arba skirtingo tipo kintamųjų rinkinys. Sintaksė: struct vardas { ; type1 var1; type2 var2;... typen varn; // C programavimo kalba 10 paskaita (Struktūros) Struktūrų sintaksė Struktūra tai vienodo arba skirtingo tipo kintamųjų rinkinys. Sintaksė: struct vardas { ; type1 var1; type2 var2;... typen varn; // Gale

More information

Lesson 26: ArrayList (W08D1)

Lesson 26: ArrayList (W08D1) Lesson 26: ArrayList (W08D1) Balboa High School Michael Ferraro October 5, 2015 1 / 25 Do Now Prepare PS #4a (paper form) for pick-up! Consider the code below for powiter(), an iterative algorithm that

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Object-Oriented Programming Intro Department of Computer Science University of Maryland, College Park Object-Oriented Programming (OOP) Approach to improving software

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

CMSC 202. Containers

CMSC 202. Containers CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.

More information

INF3110 Programming Languages Object orientation part II

INF3110 Programming Languages Object orientation part II INF3110 Programming Languages Object orientation part II 11/4/16 1 Object Orientation and Types Lecture I Lecture II - Today From predefined (simple) and user-defined (composite) types via Abstract data

More information

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes Java Generics 1 Concepts Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes 2 What Are Generics? Generics

More information

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Autumn 2013 Generics (Polymorphism) (Slides by Mike Ernst and David Notkin) 1 Varieties of abstraction Abstraction over computation: procedures int

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

Kas yra masyvas? Skaičių masyvo A reikšmės: Elementų indeksai (numeriai): Užrašymas Turbo Paskaliu: A[1] A[2] A[3] A[4] A[5]

Kas yra masyvas? Skaičių masyvo A reikšmės: Elementų indeksai (numeriai): Užrašymas Turbo Paskaliu: A[1] A[2] A[3] A[4] A[5] Masyvas 2013 1 Vienmatis masyvas Veiksmai su masyvo elementais: reikšmių priskyrimas ir išvedimas, paieška, rikiavimas. Masyvų perdavimas procedūros (funkcijos) parametrais. 2 Kas yra masyvas? Masyvu vadinamas

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping

More information

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s). AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s). a) This code will not compile because a method cannot specify an interface as a parameter. public class Testing { public static void

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

תוכנה 1 מבני נתונים גנריים

תוכנה 1 מבני נתונים גנריים תוכנה 1 מבני נתונים גנריים תרגול 8 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2 Online Resources

More information

C programavimo kalba. 3 paskaita (Sąlygos ir ciklo operatoriai, funkcija scanf() )

C programavimo kalba. 3 paskaita (Sąlygos ir ciklo operatoriai, funkcija scanf() ) C programavimo kalba 3 paskaita (Sąlygos ir ciklo operatoriai, funkcija scanf() ) Sąlygos operatorius if - else Sąlygos operatoriai skirti perduoti programos vykdymą vienai ar kitai programos šakai. Operatorius

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ ABSTRACT DATATYPES 2 Abstract Datatype (ADT)

More information

//instance variables //methods. Foo x = new Foo(); Interface: also a type of objects public interface Bar {

//instance variables //methods. Foo x = new Foo(); Interface: also a type of objects public interface Bar { BASIC CONCEPTS Class: a type of objects public class Foo { //instance variables //methods Foo x = new Foo(); Interface: also a type of objects public interface Bar { //method headers without implementation

More information

Computational Expression

Computational Expression Computational Expression ArrayList Iterators Janyl Jumadinova 7-14 November, 2018 Janyl Jumadinova Computational Expression 7-14 November, 2018 1 / 11 Collections Collection: an object that stores data;

More information

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps Today's Agenda > To give a practical introduction to data structures > To look specifically at Lists, Sets, and Maps > To talk briefly about Generics in Java > To talk about interfaces in Java Data Structures

More information

Introduction to Computer Science I

Introduction to Computer Science I Introduction to Computer Science I Iterators ArrayList Janyl Jumadinova October 31, 2016 Iterators One of the most useful operations for any collection is the ability to run through each of the elements

More information

First Name Last Name ID#

First Name Last Name ID# CIS 265 Sect 01 - V. Matos Exam-2 Spring-2015 First Name Last Name ID# (15 pts) MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) In the following

More information

Collections and Iterators. Collections

Collections and Iterators. Collections Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures

More information

generic programming alberto ferrari university of parma

generic programming alberto ferrari university of parma generic programming alberto ferrari university of parma contents generic programming java generic programming methods & generic programming classes & generic programming java with generics generic methods

More information

Advanced Programming Generics Collections

Advanced Programming Generics Collections Advanced Programming Generics Collections The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements

More information

Generics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Generics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Generics and Type Safety CS 180 Sunil Prabhakar Department of Computer Science Purdue University Dynamic Data Collections Already seen several examples of dynamic data Linked list, Stack, Queue, Trees

More information

Polymorphism: Interfaces and Iteration. Fundamentals of Computer Science

Polymorphism: Interfaces and Iteration. Fundamentals of Computer Science Polymorphism: Interfaces and Iteration Fundamentals of Computer Science Outline A shape object hierarchy Classes that extend Versus classes that implements Java interfaces How Java handles multiple-inheritance

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Information Technology and Engineering Iterator (part II) Inner class Implementation: fail-fast Version of March 20, 2011 Abstract These

More information

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface Java Collections Framework Collection: a group of elements Based Design: Software 1 with Java Java Collections Framework s s Algorithms Recitation No. 6 (Collections) 2 Collection s Online Resources Collection

More information

Everything You Ever Wanted To Know About Java O-O. 7-Dec-15

Everything You Ever Wanted To Know About Java O-O. 7-Dec-15 Everything You Ever Wanted To Know About Java O-O 7-Dec-15 Types Java has eight primitive types: short, byte, char, int, long all integral types float, double both real types, but with limited precision

More information

Taming the Tiger. Joshua Bloch, Distinguished Engineer Neal Gafter, Senior Staff Engineer Sun Microsystems. java.sun.

Taming the Tiger. Joshua Bloch, Distinguished Engineer Neal Gafter, Senior Staff Engineer Sun Microsystems. java.sun. Taming the Tiger java.sun.com/javaone/sf Joshua Bloch, Distinguished Engineer Neal Gafter, Senior Staff Engineer Sun Microsystems 1 Watch Out for Tigers! J2SE 1.5 platform Code name Tiger Beta2 available

More information

CS1083 Week 2: Arrays, ArrayList

CS1083 Week 2: Arrays, ArrayList CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08 Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics Multiple references to an array d o u b l e prices

More information

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 6 problems on the following 7 pages. You may use your single-sided handwritten 8 ½ x 11 note sheet during

More information

Java 5 New Language Features

Java 5 New Language Features Java 5 New Language Features Ing. Jeroen Boydens, BLIN prof dr. ir. Eric Steegmans http://users.khbo.be/peuteman/java5/ Enterprise Programming Last session. Jeroen Boydens 1. JDK v1.4: assert 2. Generics

More information

Java 1.5 in a Nutshell

Java 1.5 in a Nutshell Java 1.5 in a Nutshell Including Generics, Enumerated Types, Autoboxing/Unboxing, and an Enhanced for Loop http://java.sun.com/j2se/1.5.0/docs/guide/language/ CS 2334 University of Oklahoma Brian F. Veale

More information

Polymorphism (generics)

Polymorphism (generics) Polymorphism (generics) CSE 331 University of Washington Michael Ernst Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1 + y1*y1); Math.sqrt(x2*x2

More information

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CSE 331 Software Design and Implementation. Lecture 15 Generics 2 CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

The new Java 1.5. murphee (Werner Schuster)

The new Java 1.5. murphee (Werner Schuster) The new Java 1.5 murphee (Werner Schuster) http://jroller.com/page/murphee Overview Language features in 1.5 Short introduction Use/Don't use? Standard API changes Monitoring and Management Concurrent

More information

AP CS Unit 7: Interfaces. Programs

AP CS Unit 7: Interfaces. Programs AP CS Unit 7: Interfaces. Programs You cannot use the less than () operators with objects; it won t compile because it doesn t always make sense to say that one object is less than

More information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013 1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it

More information

Exam Part 3. Q.1) What is the output of the following code?

Exam Part 3. Q.1) What is the output of the following code? Q.1) What is the output of the following code? Exam Part 3 import java.util.*; // line 1 class EJavaGuruArrayList { // line 2 // line 3 ArrayList ejg = new ArrayList(); // line 4 ejg.add("one");

More information

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com JDK 7 (2011.7) JDK 7 #2 Project Coin knight76.tistory.com Knight76 at gmail.com 1 Project Coin 2 Project Leader Joseph D. Darcy( ) IDEA 2 27, 2009 3 30, 2009 (open call) 70 jdk 7, Language, The Java programming-language

More information

Review Of Fundamental Concepts (Drinking from a Fire hose 101) Object Oriented Programming and Java

Review Of Fundamental Concepts (Drinking from a Fire hose 101) Object Oriented Programming and Java Review Of Fundamental Concepts (Drinking from a Fire hose 101) 1 Object Oriented Programming and Java 2 1 Java OOP Review Topics 3 Object resuability Inheritance Composition Aggregation Encapsulation Public/Private/Protected

More information

Come to the TypeScript

Come to the TypeScript Come to the TypeScript we have type hinting! Sergej Kurakin Sergej Kurakin Amžius: 36 Dirbu: NFQ Technologies Pareigos: Programuotojas Programuoti pradėjau mokytis 1996 metais. Programuotoju dirbu nuo

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

Projektas. .h failai Header failai (interface) .m failai Pačios programos failai ( .xib /.storyboard Vartotojo sąsajos failai

Projektas. .h failai Header failai (interface) .m failai Pačios programos failai ( .xib /.storyboard Vartotojo sąsajos failai ios Projektas.h failai Header failai (interface).m failai Pačios programos failai (.xib /.storyboard Vartotojo sąsajos failai AppDelegate.h / AppDelegate.m aplikacijos pradiniai startavimo prpograminiai

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Iterator 1 (part I) Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 26, 2013 Abstract These lecture notes are meant to be looked

More information