Java for Interfaces and Networks (DT3029)

Size: px
Start display at page:

Download "Java for Interfaces and Networks (DT3029)"

Transcription

1 Java for Interfaces and Networks (DT3029) Lecture 4 Networking with Threads and Containers Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University, Sweden ContainerAlliance.com

2 The case for threads in client/server apps In the echo server example in the previous lecture, both client and server had a single thread server listens to on a port, and then gives all its attention to the first client that connects client is either reading form keyboard or sending/waiting for response from server Multi-threaded chat server a server through which multiple clients can chat server can serve many clients (i.e., has a thread that listens for connections) client has two threads: one for user input, one for communicating with the server 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 2 / 29

3 Multi-threaded chat server 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

4 Multi-threaded chat server 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

5 Multi-threaded chat server MultiServer.java 1 public class MultiServer { 2 public static final int PORT = 2000; 3 public static void main(string[] args) throws IOException { 4 ServerSocket s = new ServerSocket(PORT); 5 System.out.println("Server socket: " + s); 6 System.out.println("Server listening..."); 7 try { while(true) { 8 // Blocks until a connection occurs: 9 Socket socket = s.accept(); 10 System.out.println("Connection accepted."); 11 System.out.println("The new socket: " + socket); 12 //continues F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

6 Multi-threaded chat server MultiServer.java (cont.) 13 try { 14 ClientThread t = new ClientThread(socket); 15 System.out.println("New thread started."); 16 System.out.println("The new thread: " + t); 17 } 18 catch(ioexception e) { 19 // If the constructor fails, close the socket, 20 // otherwise the thread will close it: 21 socket.close(); 22 } } } //catch, while, try 23 finally { s.close(); } 24 } //main 25 } //MultiServer 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

7 Multi-threaded chat server 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

8 Multi-threaded chat server ClientThread.java 1 import...; 2 class ClientThread extends Thread { 3 private static int numberofclients = 0; 4 private static ArrayList<ClientThread> allclients = 5 new ArrayList<ClientThread>(); 6 private final int clientnumber = ++numberofclients; 7 private final Socket socket; 8 private final BufferedReader in; 9 private final PrintWriter out; 10 public ClientThread(Socket s) throws IOException { 11 socket = s; 12 in = new BufferedReader( 13 new InputStreamReader(socket.getInputStream())); 14 out = new PrintWriter( 15 new BufferedWriter( 16 new OutputStreamWriter( 17 socket.getoutputstream())), true); 18 //continues F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

9 Multi-threaded chat server ClientThread.java (cont.) 19 System.out.println("Client thread " + clientnumber + 20 " created."); 21 out.println("welcome. You are client number " + 22 clientnumber + "."); 23 allclients.add(this); 24 // If any of the above calls throw an 25 // exception, the caller is responsible for 26 // closing the socket. Otherwise the thread 27 // will close it. 28 start(); //Starts the thread, and calls run() 29 } 30 //continues F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

10 Multi-threaded chat server ClientThread.java (cont.) 31 public void run() { 32 try { 33 while (true) { 34 String inline = in.readline(); 35 System.out.println("Client thread " + clientnumber + 36 " received: " + inline); 37 if (inline == null inline.equals("quit")) break; 38 out.println("you said " + inline + " "); 39 Iterator<ClientThread> i = allclients.iterator(); 40 while (i.hasnext()) { 41 ClientThread t = i.next(); 42 if (t!= this) 43 t.out.println("from client " + clientnumber + 44 ": " + inline); 45 } } //while, while 46 System.out.println("Client thread " + clientnumber + 47 ": exiting..."); 48 } 49 //continues F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

11 Multi-threaded chat server ClientThread.java (cont.) 50 catch(ioexception e) { 51 System.out.println("Client thread " + clientnumber + 52 ": I/O error"); 53 } 54 finally { 55 try { socket.close(); } 56 catch(ioexception e) { 57 System.out.println("Client thread " + clientnumber + 58 ": Socket not closed!"); 59 } 60 allclients.remove(allclients.indexof(this)); 61 } //finally 62 } //run 63 } //class ClientThread 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

12 Multi-threaded chat server 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

13 Multi-threaded chat server Client2.java 1 import...; 2 public class Client2 { 3 public static final int PORT = 2000; 4 public static void main(string[] args) throws IOException { 5 InetAddress addr; 6 if (args.length >= 1) 7 addr = InetAddress.getByName(args[0]); 8 else 9 addr = InetAddress.getByName(null); 10 Socket socket = new Socket(addr, PORT); 11 System.out.println("The new socket: " + socket); 12 BufferedReader in = new BufferedReader( 13 new InputStreamReader(socket.getInputStream())); 14 PrintWriter out = new PrintWriter( 15 new BufferedWriter( 16 new OutputStreamWriter( 17 socket.getoutputstream())), true); 18 //continues F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

14 Multi-threaded chat server Client2.java (cont.) 19 BufferedReader kbd_reader = new BufferedReader( 20 new InputStreamReader(System.in)); 21 ServerListener t = new ServerListener(in); 22 t.start(); 23 String buf; 24 while (true) { 25 buf = kbd_reader.readline(); 26 System.out.println("User input: " + buf); 27 System.out.println("To server: " + buf); 28 out.println(buf); 29 } 30 } //main 31 } //class Client F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

15 Multi-threaded chat server 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

16 Multi-threaded chat server ServerListener.java 1 import...; 2 final class ServerListener extends Thread { 3 final private BufferedReader fromserver; 4 public ServerListener(BufferedReader fromserver) { 5 this.fromserver = fromserver; 6 } 7 public void run() { 8 String linefromserver; 9 try { 10 while ((linefromserver = fromserver.readline())!= null 11 &&!linefromserver.equals("quit")) { 12 System.out.println("From server: " + linefromserver); 13 } 14 } 15 catch (IOException e) {... } 16 } //run 17 } //class ServerListener 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 3 / 29

17 What are containers? A container is an object that can contain other objects In Java 1.2 (Java 2) many new types of container classes were introduced, e.g., ArrayList Container classes can contain any type of object you have to cast to the object type when retrieving it Java provides a number of containers for lists, sets and maps list = an ordered collection of objects (interface List) set = a collection that contains no duplicate elements (interface Set) map = a mapping from keys to values, a look-up table (interface Map) All container classes extend class Collection 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 4 / 29

18 Common types of containers for lists Interface List: dynamic size, add to specific location, delete, search, iteration Class Vector (implements List): O(n) put/remove, O(1) get, thread-safe Class ArrayList (implements List): O(n) put/remove, O(1) get, non-thread-safe Class LinkedList (implements List): O(1) put/remove, O(n) get NB: primitive type arrays have fixed size and are simplest, but fastest (if you know what you are doing)... and you can use the convenience methods of class Arrays 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 5 / 29

19 Common types of containers for sets Interface Set: dynamic size, add, delete, search, iteration Class HashSet (implements Set): an un-sorted set (implemented as a HashMap), O(1) get/put, O(n) remove Class TreeSet (implements Set): a sorted set (implemented as a TreeMap), O(log(n)) get/put/remove 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 6 / 29

20 Common types of containers for mappings Interface Map: dynamic size, add, delete, search, iteration Class HashMap (implements Map): Hash table based implementation of the Map interface, O(1) get/put, O(n) remove Class TreeMap (implements Map): binary tree based implementation of the Map interface, O(log(n)) get/put/remove 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 7 / 29

21 Containers: overview 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 8 / 29

22 Containers: package java.util import java.util.arraylist; import java.util.iterator; import java.util.linkedlist; import java.util.hashset; import java.util.treeset; import java.util.hashmap; import java.util.treemap; Containers cannot contain primitive types (except primitive type arrays) Containers can contain any kind of Object Underlying implementation of Vector and ArrayList is an array 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 9 / 29

23 Containers: primitive type arrays The built-in arrays are easiest, and sometimes the Java API imposes their use 1 public static void main(string[] args) { 2 for (int i = 0; i < args.length; ++i) 3 System.out.println("Arg. " + i + ": " + args[i] + " "); 4 } 5 } Arrays need to be allocated with new 1 int[] intarray1 = new int[10]; 2 int intarray2[] = new int[10]; 3 String[] fruits = { "Apple", "Pear", "Orange" }; 4 int intarray[10]; // Compilation error: ] expected 5 fruits = new String[] { "Pineapple", "Banana" }; 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 10 / 29

24 Convenience methods in class Arrays java.util.arrays provides convenient methods for manipulating arrays 1 java.util.arrays.sort(fruits); 2 java.util.arrays.fill(fruits, "Lemon"); You can also make arrays of non-primitive types 1 Hamster[] ha1 = 2 { new Hamster("Adam"), new Hamster("Bertil"), 3 new Hamster("Kate") }; 4 for (int i = 0; i < ha1.length; ++i) 5 System.out.println("ha1[" + i + "]: " + ha1[i] + " "); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 11 / 29

25 Convenience methods in class Arrays Assuming we have defined tostring() in class Hamster... linux> java HamsterTest ha1[0]: Hamster-Adam ha1[1]: Hamster-Bertil ha1[2]: Hamster-Kate You can also allocate arrays first and then fill them in 1 Hamster[] ha2 = new Hamster[4]; 2 ha2[0] = new Hamster("Anna"); 3 ha2[1] = new Hamster("Beata"); 4 ha2[2] = new Hamster("Cecilia"); 5 ha2[3] = new Hamster("Dora"); 6 ha2[4] = new Hamster("Fredrik"); // Runtime exception 7 ha2[2] = new Boat("Titanic"); // Compilation error 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 12 / 29

26 Convenience methods in class Arrays Assuming we have defined compareto() in class Hamster... 1 Arrays.sort(ha1); 2 Arrays.sort(ha2); Assuming we have defined equals() in class Hamster... 1 if (Arrays.equals(ha1, ha2)) 2 System.out.println("The two arrays are equal"); 3 else if (ha1.length == ha2.length) 4 System.out.println("There is at least one pair 5 of different elements"); 6 else 7 System.out.println("The two arrays have 8 different lengths"); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 13 / 29

27 A different kind of array : ArrayList ArrayLists are a better choice if one needs a dynamic array, i.e., an array whose size can increase or decrease during execution When instantiated, the list is empty, and objects are added through the add() method The get() method retrieves objects in a given position 1 ArrayList<Boat> boats = new ArrayList<Boat>(); 2 Boat b1 = new Boat("Titanic"); 3 Boat b2 = new Boat("Exxon Valdez"); 4 Boat b3 = new Boat("Torrey Canyon"); 5 boats.add(b1); 6 boats.add(b2); 7 boats.add(b3); 8 boats.add(b1); 9 boats.add(b1); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 14 / 29

28 A different kind of array : ArrayList ArrayLists are a better choice if one needs a dynamic array, i.e., an array whose size can increase or decrease during execution When instantiated, the list is empty, and objects are added through the add() method The get() method retrieves objects in a given position 1 System.out.println("Boats (1):"); 2 for (int i = 0; i < boats.size(); ++i) 3 System.out.println(" boats[" + i + "]: " + boats.get(i)); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 14 / 29

29 A different kind of array : ArrayList ArrayLists are a better choice if one needs a dynamic array, i.e., an array whose size can increase or decrease during execution When instantiated, the list is empty, and objects are added through the add() method The get() method retrieves objects in a given position linux> java BoatTest Boats (1): boats[0]: Boat Titanic boats[1]: Boat Exxon Valdez boats[2]: Boat Torrey Canyon boats[3]: Boat Titanic boats[4]: Boat Titanic 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 14 / 29

30 A different kind of array : ArrayList Instead of using an int to cycle through the ArrayList and retrieve elements with get(), we can use an Iterator Iterators provide methods hasnext() and next() to access elements in the ArrayList 1 System.out.println("Boats (2):"); 2 Iterator i1 = boats.iterator(); 3 while (i1.hasnext()) 4 System.out.println(" A boat: " + i1.next()); We can for instead of while to limit the scope of the iterator to the loop 1 System.out.println("Boats (3):"); 2 for (Iterator i = boats.iterator(); i.hasnext(); ) 3 System.out.println(" A boat: " + i.next()); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 15 / 29

31 A different kind of array : ArrayList Instead of using an int to cycle through the ArrayList and retrieve elements with get(), we can use an Iterator Iterators provide methods hasnext() and next() to access elements in the ArrayList 1 System.out.println("Boats (2):"); 2 Iterator i1 = boats.iterator(); 3 while (i1.hasnext()) 4 System.out.println(" A boat: " + i1.next()); Even more practical: we can use the for-each loop 1 System.out.println("Boats (4):"); 2 for (Boat i : boats) { 3 System.out.println(" A boat: " + i); 4 } 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 15 / 29

32 A different kind of array : ArrayList The method indexof() returns the index of the first occurrence of an object, or -1 if the object is not found in the list Comaprison depends on implementation of equals() Hamster.java 1 class Hamster { public boolean equals(object o) { 4 if (!(o instanceof Hamster)) return false; 5 return (o.getname().equals(this.name)); 6 } } 1 System.out.println("Hasse s position (1): " + 2 hamsters.indexof(hasse)); 3 System.out.println("Hasse s position (2): " + 4 hamsters.indexof(new Hamster("Hasse"))); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 16 / 29

33 A different kind of array : ArrayList The method remove() deletes an object from the list The object can be indicated both by index and by reference The latter depends on implementation of equals() Hamster.java 1 class Hamster { public boolean equals(object o) { 4 if (!(o instanceof Hamster)) return false; 5 return (o.getname().equals(this.name)); 6 } } 1 // Remove element in position 4 2 boats.remove(4); 3 // Remove the first occurrence of boat Titanic 4 boats.remove(b1); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 17 / 29

34 ArrayList vs. Vector The two classes are almost identical if seen from the outside Nonetheless, some significant differences are present synchronization: Vectors are synchronized, ArrayLists are not the latter are slightly faster data growth: inserting an element into either type of objectcan trigger an expansion of the internal array size a Vector doubles the size of its array, while the ArrayList increases its array size by 50% Note that all methods and usage patterns shown for ArrayList work for Vector! 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 18 / 29

35 Containers and generics Container classes can contain any type of object You have to cast to the object type when retrieving it Java 1.5 (Java 5.0) introduced generics No generics 1 // Removes 4-letter words from c. Elements must be strings 2 static void expurgate(arraylist c) { 3 for (Object o : c) 4 if (((String) o).length() == 4) 5 c.remove(o); 6 } Inconvenient to have to cast all the time The compiler cannot check that you are casting to the right type 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 19 / 29

36 Containers and generics Generics provides a way for you to communicate the type of a collection to the compiler Avoids the need to cast With generics 1 // Removes 4-letter words from c. 2 static void expurgate(arraylist<string> c) { 3 for (String o : c) 4 if (o.length() == 4) 5 c.remove(o); 6 } Code using generics is safer and clearer eliminates an unsafe cast moves part of the specification of the method from a comment to its signature 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 20 / 29

37 A different kind of array : LinkedList Both ArrayList and LinkedList implement the interface List They have the same methods, but differ in performance The internal representation of LinkedList is, though, very different from that of ArrayList and Vector 1 // A LinkedList is like an ArrayList 2 LinkedList<Boat> boatlist = new LinkedList<Boat>(); 3 for (Iterator<Boat> i = boats.iterator(); i.hasnext(); ) 4 boatlist.add(i.next()); 5 boatlist.addall(boats); // All at once! 6 System.out.println("Boats in the boatlist:"); 7 for (Iterator<Boat> i = boatlist.iterator(); i.hasnext(); ) 8 System.out.println(" A boat: " + i.next()); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 21 / 29

38 Sets with class HashSet A set cannot contain doubles Elements in a set are not ordered... well, they are ordered because you insert them is a specific order, but you have no guarantee that this order is maintained in the internal representation! Both HashSet and TreeSet implement the interface Set the two classes can do the same things, but have different performance 1 // A HashSet is a set, so no duplicates 2 HashSet<Boat> boatset = new HashSet<Boat>(); 3 for (Iterator<Boat> i = boats.iterator(); i.hasnext(); ) 4 boatset.add(i.next()); 5 boatset.addall(boats); // All at once! 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 22 / 29

39 Sets with class HashSet A set cannot contain doubles Elements in a set are not ordered... well, they are ordered because you insert them is a specific order, but you have no guarantee that this order is maintained in the internal representation! Both HashSet and TreeSet implement the interface Set the two classes can do the same things, but have different performance 1 System.out.println("Boats in the boatset:"); 2 for (Iterator<Boat> i = boatset.iterator(); i.hasnext(); ) 3 System.out.println(" A boat: " + i.next()); 4 boatset.remove(b1); 5 System.out.println("After removal from boatset:"); 6 for (Iterator<Boat> i = boatset.iterator(); i.hasnext(); ) 7 System.out.println(" A boat: " + i.next()); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 22 / 29

40 Sets with class HashSet A set cannot contain doubles Elements in a set are not ordered... well, they are ordered because you insert them is a specific order, but you have no guarantee that this order is maintained in the internal representation! Both HashSet and TreeSet implement the interface Set the two classes can do the same things, but have different performance linux> java BoatTest Boats in the boatset: A boat: Boat Titanic A boat: Boat Exxon Valdez A boat: Boat Torrey Canyon After removal from boatset: A boat: Boat Exxon Valdez A boat: Boat Torrey Canyon 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 22 / 29

41 Another type of set: TreeSet Both HashSet and TreeSet implement the interface Set They have the same methods, but differ in performance TreeSet maintains data as a binary tree, thus making it suited for binary tree search thus, Objects inserted into a TreeSet should implement the interface Comparable (in order to have the method compareto()) 1 HashSet<Phonenumber> phonenumberset1 = 2 new HashSet<Phonenumber>(); 3 phonenumberset1.add(new Phonenumber(116090)); 4 phonenumberset1.add(new Phonenumber(271010)); 5 phonenumberset1.add(new Phonenumber(271011)); 6 phonenumberset1.add(new Phonenumber(271012)); 7 phonenumberset1.add(new Phonenumber(111111)); 8 phonenumberset1.add(new Phonenumber(111111)); 9 phonenumberset1.add(new Phonenumber(111111)); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 23 / 29

42 Another type of set: TreeSet Both HashSet and TreeSet implement the interface Set They have the same methods, but differ in performance TreeSet maintains data as a binary tree, thus making it suited for binary tree search thus, Objects inserted into a TreeSet should implement the interface Comparable (in order to have the method compareto()) 1 System.out.println("Phonenumber in phonenumberset 1:"); 2 for (Iterator<Phonenumber> i = 3 telephonenumberset1.iterator(); i.hasnext(); ) 4 System.out.println(" A phonenumber: " + i.next()); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 23 / 29

43 Another type of set: TreeSet Both HashSet and TreeSet implement the interface Set They have the same methods, but differ in performance TreeSet maintains data as a binary tree, thus making it suited for binary tree search thus, Objects inserted into a TreeSet should implement the interface Comparable (in order to have the method compareto()) linux> java PhonenumeberTest Phonenumber in phonenumberset 1: A phonenumber: +46-(0) A phonenumber: +46-(0) A phonenumber: +46-(0) A phonenumber: +46-(0) A phonenumber: +46-(0) F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 23 / 29

44 Mappings with class HashMap A mapping (or map) is sometimes calle a dictionary or a look-up table Every elements in a mapping consists of a key and a value Knowing the key allows to obtain the value quickly 1 HashMap<String, Phonenumber> phnbk = 2 new HashMap<String, Phonenumber>(); 3 phnbk.put("anna", new Phonenumber(116090)); 4 phnbk.put("bengt", new Phonenumber(224000)); 5 phnbk.put("conny", new Phonenumber(125566)); 6 phnbk.put("doris", new Phonenumber(171045)); 7 phnbk.put("eberhart", new Phonenumber(111111)); 8 phnbk.put("eberhart", new Phonenumber(222222)); 9 phnbk.put("eberhart", new Phonenumber(333333)); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 24 / 29

45 Mappings with class HashMap A mapping (or map) is sometimes calle a dictionary or a look-up table Every elements in a mapping consists of a key and a value Knowing the key allows to obtain the value quickly 1 System.out.println("Conny s number " + phnbk.get("conny")); 2 System.out.println("Phonebook 1:"); 3 for (Iterator<String> i = phnbk.keyset().iterator(); 4 i.hasnext(); ) { 5 String namn = i.next(); 6 System.out.println(" " + name + " s number: " + 7 phnbk.get(name)); 8 } 9 System.out.println("Phonebook 1, again:"); 10 for (String i : phnbk.keyset()) { 11 System.out.println(" " + i + " s number: " + phnbk.get(i)); 12 } 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 24 / 29

46 Mappings with class HashMap A mapping (or map) is sometimes calle a dictionary or a look-up table Every elements in a mapping consists of a key and a value Knowing the key allows to obtain the value quickly Conny s number: +46-(0) Phonebook 1: Doris s number: +46-(0) Eberhart s number: +46-(0) Conny s number: +46-(0) Bengt s number: +46-(0) Anna s number: +46-(0) Phonebook 1, again: Doris s number: +46-(0) Eberhart s number: +46-(0) Conny s number: +46-(0) Bengt s number: +46-(0) Anna s number: +46-(0) F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 24 / 29

47 Another type of map: TreeMap Both HashMap and TreeMap implement the interface Map They have the same methods, but differ in performance TreeMap maintains data as a binary tree, thus making it suited for binary tree search thus, Objects inserted into a TreeMap should implement the interface Comparable (in order to have the method compareto()) 1 // String implements Comparable... 2 TreeMap<String, Phonenumber> phnbk1 = 3 new TreeMap<String, Telefonnummer>(); 4 phnbk1.put("anna", new Phonenumber(116090)); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 25 / 29

48 Primitive types in containers Java containers cannot contain primitive types (except for primitive arrays) 1 // Compilation error: "unexpected type" 2 ArrayList<int> numbers = new ArrayList<int>(); But Java provides boxed variants of primitive types int Integer long Long float Float double Double boolean Boolean byte Byte F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 26 / 29

49 Auto-boxing and Auto-unboxing When inserting into a container, you would need to instantiate the boxed type from your primitive type 1 ArrayList<Integer> numbers = new ArrayList<Integer>(); 2 int[] numberarray = { 5, 3, 7, 12, 4 }; 3 for (int i : numberarray) 4 numbers.add(new Integer(i)); When you retrieve you would need to use xxxvalue() method... 1 int[] numberarray = new int[numbers.size()]; 2 for (int i = 0; i < numbers.size(); i++) 3 numberarray[i] = numbers.get(i).intvalue(); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 27 / 29

50 Auto-boxing and Auto-unboxing Auto-boxing allows you to avoid instantiating the boxed type 1 ArrayList<Integer> numbers = new ArrayList<Integer>(); 2 int num4 = 4; 3 numbers.add(num4); 4 numbers.add(5); Auto-unboxing allows you to avoid calling a method 1 System.out.println("Numbers in ArrayList<Integer>:"); 2 for (int i : numbers) 3 System.out.println(" A number " + i); 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 28 / 29

51 Networking with Threads and Containers Thank you! 2014 F. Pecora, T.P. McCarthy / Örebro University aass.oru.se 29 / 29

Java for Interfaces and Networks (DT3010, HT11)

Java for Interfaces and Networks (DT3010, HT11) Java for Interfaces and Networks (DT3010, HT11) Networking with Threads and Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces

More information

Java for Interfaces and Networks (DT3029)

Java for Interfaces and Networks (DT3029) Java for Interfaces and Networks (DT3029) Lecture 3 Threads and Networking Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University, Sweden Capiscum

More information

Java for Interfaces and Networks

Java for Interfaces and Networks Java for Interfaces and Networks Threads and Networking Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks Lecture

More information

Java for Interfaces and Networks (DT3010, HT10)

Java for Interfaces and Networks (DT3010, HT10) Java for Interfaces and Networks (DT3010, HT10) Inner Classes Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks

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

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed 1 1 COMP200 GENERICS OOP using Java, from slides by Shayan Javed 2 ArrayList and Java Generics 3 Collection A container object that groups multiple objects 4 Collection A container object that groups multiple

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

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections Course Name: Advanced Java Lecture 8 Topics to be covered Collections Introduction A collection, sometimes called a container, is simply an object that groups multiple elements into a single unit. Collections

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

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011 1 ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES Lecture 4 CS 2110 Summer 2011 Lists are Iterable 4 for public static void printlist(list strings) { for (int idx = 0; idx < strings.size();

More information

Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL

Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 What is a thread Why use multiple threads Issues and problems involved Java threads Natasha Alechina School of Computer

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

Network Programming. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Network Programming. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Network Programming by Vlad Costel Ungureanu for Learn Stuff Java Network Protocols 2 Java Network Protocols 3 Addresses Innet4Address (32-bit) 85.122.23.145 - numeric pentalog.com symbolic Innet6Address

More information

Topic 10: The Java Collections Framework (and Iterators)

Topic 10: The Java Collections Framework (and Iterators) Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of

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

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

public static void main(string[] args) throws IOException { sock = new Socket(args[0], Integer.parseInt(args[1]));

public static void main(string[] args) throws IOException { sock = new Socket(args[0], Integer.parseInt(args[1])); Echo Client&Server Application EchoClient import java.net.*; import java.io.*; class EchoClient public static void main(string[] args) throws IOException if (args.length < 2) number>"); System.err.println("Usage:

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Fundamental language mechanisms

Fundamental language mechanisms Java Fundamentals Fundamental language mechanisms The exception mechanism What are exceptions? Exceptions are exceptional events in the execution of a program Depending on how grave the event is, the program

More information

Java for Interfaces and Networks (DT3029)

Java for Interfaces and Networks (DT3029) Java for Interfaces and Networks (DT3029) Lecture 1 Introduction and Basics Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University, Sweden Image source:

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

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS Core Java SYLLABUS COVERAGE Introduction. OOPS Package Exception Handling. Multithreading Applet, AWT, Event Handling Using NetBean, Ecllipse. Input Output Streams, Serialization Networking Collection

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

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

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

CITS1001 week 6 Libraries

CITS1001 week 6 Libraries CITS1001 week 6 Libraries Arran Stewart April 12, 2018 1 / 52 Announcements Project 1 available mid-semester test self-assessment 2 / 52 Outline Using library classes to implement some more advanced functionality

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

MODULE 6q - Exceptions

MODULE 6q - Exceptions MODULE 6q - Exceptions THE TRY-CATCH CONSTRUCT Three different exceptions are referred to in the program below. They are the ArrayIndexOutOfBoundsException which is built-into Java and two others, BadLuckException

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

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

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

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

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure. Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

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

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write

More information

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary CPSC 441 Tutorial TCP Server Department of Computer Science University of Calgary TCP Socket Client Server Connection Request Server Listening on welcoming socket Client Socket Server Socket Data Simple

More information

CS2307 NETWORKS LAB 1. Programs using TCP Sockets (like date and time server & client, echo server & client, etc.) 2. Programs using UDP Sockets

CS2307 NETWORKS LAB 1. Programs using TCP Sockets (like date and time server & client, echo server & client, etc.) 2. Programs using UDP Sockets CS2307 NETWORKS LAB 1. Programs using TCP Sockets (like date and time server & client, echo server & client, etc.) 2. Programs using UDP Sockets (like simple DNS) 3. Programs using Raw sockets (like packet

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

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

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1 Today: Java Library Classes for lists. Iterators, ListIterators CS61B Lecture #7 Last modified: Fri Sep 12 14:41:31 2008 CS61B: Lecture #7 1 Abstracting Listness So far, we ve seen fairly primitive types

More information

Java Input/Output. 11 April 2013 OSU CSE 1

Java Input/Output. 11 April 2013 OSU CSE 1 Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 Name: This exam consists of 5 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

Java Networking (sockets)

Java Networking (sockets) Java Networking (sockets) Rui Moreira Links: http://java.sun.com/docs/books/tutorial/networking/toc.html#sockets http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets_p.html Networking Computers

More information

Object-Oriented Design and Programming (Java)

Object-Oriented Design and Programming (Java) Object-Oriented Design and Programming (Java) Topics Covered Today 2.2 Collections 2.2.1 Arrays 2.2.2 Vectors and Iterators 2.2.3 Implementing the Collections of the Library System 2 What is a Collection?

More information

Highlights of Previous Lecture

Highlights of Previous Lecture Highlights of Previous Lecture Inheritance vs. Composition IS-A-KIND-OF vs. HAS-A relationships Java vs. C++: differences in ability to access base class behavior Interfaces as contracts, as types, supporting

More information

5 More sophisticated behavior

5 More sophisticated behavior Main concepts to be covered 5 More sophisticated behavior Using library classes to implement some more advanced functionality BK Chap. 6 Maps and sets Random number generation Equality vs identity Class

More information

Week 13 Lab - Exploring Connections & Remote Execution

Week 13 Lab - Exploring Connections & Remote Execution Week 13 Lab - Exploring Connections & Remote Execution COSC244 & TELE202 1 Assessment This lab is worth 0.5%. The marks are awarded for completing the programming exercise and answering the questions.

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

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

JAVA WRAPPER CLASSES

JAVA WRAPPER CLASSES JAVA WRAPPER CLASSES Description Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of

More information

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods Adam Blank Lecture 5 Winter 2019 CS 2 Introduction to Programming Methods CS 2: Introduction to Programming Methods Java Collections Abstract Data Types (ADT) 1 Abstract Data Type An abstract data type

More information

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013 Name: This exam consists of 5 problems on the following 6 pages. You may use your double-sided hand-written 8 ½ x 11 note sheet

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

Introduction to Sockets

Introduction to Sockets Introduction to Sockets Sockets in Java 07/02/2012 EPL 602 1 Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API o introduced in BSD4.1 UNIX,

More information

COMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming

COMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming COMP 213 Advanced Object-oriented Programming Lecture 20 Network Programming Network Programming A network consists of several computers connected so that data can be sent from one to another. Network

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017 COMP 250 Lecture 32 interfaces (Comparable, Iterable & Iterator) Nov. 22/23, 2017 1 Java Comparable interface Suppose you want to define an ordering on objects of some class. Sorted lists, binary search

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

Java for Interfaces and Networks (DT3010, HT11)

Java for Interfaces and Networks (DT3010, HT11) Java for Interfaces and Networks (DT3010, HT11) Introduction Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks Lecture

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

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students.  Collections. Play with problem set 1 Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So

More information

Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Network Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@ase.au.dk Outline Socket programming If we have the time: Remote method invocation (RMI) 2 Socket Programming Sockets

More information

Internet Technology 2/7/2013

Internet Technology 2/7/2013 Sample Client-Server Program Internet Technology 02r. Programming with Sockets Paul Krzyzanowski Rutgers University Spring 2013 To illustrate programming with TCP/IP sockets, we ll write a small client-server

More information

Software 1 with Java. Recitation No. 6 (Collections)

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

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

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

Chapter 11: Collections and Maps

Chapter 11: Collections and Maps Chapter 11: Collections and Maps Implementing the equals(), hashcode() and compareto() methods A Programmer's Guide to Java Certification (Second Edition) Khalid A. Mughal and Rolf W. Rasmussen Addison-Wesley,

More information

Core Java Contents. Duration: 25 Hours (1 Month)

Core Java Contents. Duration: 25 Hours (1 Month) Duration: 25 Hours (1 Month) Core Java Contents Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing a Java Application at command prompt Java

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

CS 310: Maps and Sets

CS 310: Maps and Sets CS 310: Maps and Sets Chris Kauffman Week 9-1 Logistics Goals Today HW2 Discussion Maps and Sets HW2 Discussion Milestones due Thu 7/6 Discuss AdditiveList Iterator Implementation O(1) Undo/Redo Reading

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

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

NAME: c. (true or false) The median is always stored at the root of a binary search tree. EE 322C Spring 2009 (Chase) Exam 2: READ THIS FIRST. Please use the back side of each page for scratch paper. For some of the questions you may need to think quite a bit before you write down an answer.

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

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

CS Programming Language Java. Fall 2004 Sept. 29

CS Programming Language Java. Fall 2004 Sept. 29 CS3101-3 Programming Language Java Fall 2004 Sept. 29 Road Map today Java review Homework review Exception revisited Containers I/O What is Java A programming language A virtual machine JVM A runtime environment

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

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

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

Tony Valderrama, SIPB IAP 2010

Tony Valderrama, SIPB IAP 2010 Today Java API java.util java.io More OOP Generics Enum.jar files JNI Q & A Announcements Course website: http://sipb.mit.edu/iap/java/ Email: sipb-iap-java@mit.edu package java.io Images from the Java

More information

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani The Collection Framework Collection: an aggregate that can hold a varying number of elements Interface:

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

Java for Interfaces and Networks (DT3010, HT10)

Java for Interfaces and Networks (DT3010, HT10) Java for Interfaces and Networks (DT3010, HT10) More Basics: Classes, Exceptions, Garbage Collection, Interfaces, Packages Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se

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

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Section: You have 180 minutes to complete this exam. For coding questions, you do

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 16 References and linked nodes reading: 16.1 2 Value semantics value semantics: Behavior where values are copied when assigned, passed as parameters, or returned. All primitive

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

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() );

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() ); Advanced Java Concepts Maps and Sets and Miscellany Exercises and Programs 1. This code a) contains a compiler error. b) contains a runtime error. c) displays 1 d) displays 2 2. This code a) contains a

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

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

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

23 Sorting a text file using an ArrayList 24 The SortList class? 26 The SortList class? 27 Collections API: Collections class 30 The SortList class? 3

23 Sorting a text file using an ArrayList 24 The SortList class? 26 The SortList class? 27 Collections API: Collections class 30 The SortList class? 3 List of Slides 1 Title 2 Chapter 21: Collections 3 Chapter aims 4 Section 2: Example:Reversing a text file 5 Aim 6 Reversing a text file 7 Collections API 8 Collections API: Lists 9 Collections API: Lists:

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

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design I/O subsystem API Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 10, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction to Java

More information

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748 COT 3530: Data Structures Giri Narasimhan ECS 389; Phone: x3748 giri@cs.fiu.edu www.cs.fiu.edu/~giri/teach/3530spring04.html Evaluation Midterm & Final Exams Programming Assignments Class Participation

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

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design I/O subsystem API Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 10, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction to Java

More information

Highlights of Last Week

Highlights of Last Week Highlights of Last Week Refactoring classes to reduce coupling Passing Object references to reduce exposure of implementation Exception handling Defining/Using application specific Exception types 1 Sample

More information