SlideShare a Scribd company logo
1 of 28
LAB #8
Prepared by: Berk Soysal
2016 Winter
 Often, you will want to cycle through the elements in a
collection. For example, you might want to display each
element or remove an element.
 The easiest way to do this is to employ an iterator, which is
an object that implements either the Iterator or the
ListIterator interface.
2016 Winter
Iterator ListIterator
Unidirectional (forward iteration)
Has only next()
Bidirectional (forward and backward iteration)
Has next() and previous()
Map, List, Set implemented Objects List implemented Objects only
remove() only add(), remove()
Cannot determine current position of
the iterator
Can determine the current position of the
iterator
2016 Winter
 The Iterator interface specifies 3 methods:
boolean hasNext()
//returns true if this iteration has more elements
E next()
//returns the next element in this iteration
//pre: hastNext()
void remove()
/*Removes from the underlying collection the last element
returned by the iterator.
pre: This method can be called only once per call to next.
After calling, must call next again before calling remove
again.
*/
2016 Winter
Imagine a fence made up of fence posts
and rail sections.
fenceposts
rails
2016 Winter
 The iterator lives on the fence posts
 The data in the collection are the rails
 Iterator created at the far left post
 As long as a rail exists to the right of the Iterator,
hasNext() is true
iterator object
2016 Winter
ArrayList<String> names =new ArrayList<String>();
names.add(“Alex”);
names.add(“Liz”);
names.add(“Tim”);
names.add(“Jack”);
Iterator<String> it = names.iterator();
int i = 0;
iterator object
“Alex” “Liz” “Tim” “Jack”
2016 Winter
“Alex” “Liz” “Tim” “Jack”
while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 1, prints out Alex
 first call to next
moves iterator to
next post and
returns “Alex”
2016 Winter
“Alex” “Liz” “Tim” “Jack”
while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 2, prints out Liz
2016 Winter
“Alex” “Liz” “Tim” “Jack”
while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 3, prints out Tim
2016 Winter
“Alex” “Liz” “Tim” “Jack”
while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// when i == 4, prints out Jack
2016 Winter
“Alex” “Liz” “Tim” “Jack”
while( it.hasNext() ) {
i++;
System.out.println( it.next() );
}
// while loop stops since call to hasNext
returns false
2016 Winter
 An Iterator can be used to remove things from the Collection
 Can only be called once per call to next()
public void removeWordsOfLength(int len) {
Iterator<String> it = myList.iterator();
while( it.hasNext() ) {
String temp = it.next();
if(temp.length() == len)
it.remove();
}
}
// myList = [“dogs”, “cat”, “hats”, “bikes”]
// resulting list after removeWordsOfLength(3) ?
2016 Winter
 In Java, just like methods, variables of a class too can
have another class as its member. Writing a class within
another is allowed in Java.
 The class written within is called the nested class, and
the class that holds the inner class is called the outer
class.
class OuterClass{
class InnerClass{
}
}
 Inner classes are a security mechanism in Java.
2016 Winter
 We know a regular class cannot be associated with the
access modifier private, but if we have the class as a
member of other class, then the inner class
can be made private.
2016 Winter
You are provided an almost complete implementation of a
class. Complete the implementation of the class BitList.
public BitList( String s ); creates a list of bits representing the input
string s. The given string, s, must be a string of 0s and 1s, otherwise the
constructor must throw an exception of type IllegalArgumentException.
This constructor initializes the new BitList instance to represent the value
in the string. Each character in the string represents one bit of the list,
with the rightmost character in the string being the low order bit.
For example, given the string “1010111” the constructor should initialize
the new BitList to include this list of bits:
-> 1 -> 1 -> 1 -> 0 -> 1 -> 0 -> 1
2016 Winter
Use the class called Iterative. Implement the methods below. Your
solutions must be iterative (i.e. uses iterators).
2016 Winter
2016 Winter
2016 Winter
• Map: an unordered collection that associates a
collection of element values with a set of keys so
that elements they can be found very quickly (O(1)!)
– Each key can appear at most once (no duplicate keys)
– A key maps to at most one value
– the main operations:
• put(key, value)
"Map this key to that value."
• get(key)
"What value, if any, does this key map to?"
– maps are also called:
• hashes or hash tables
• dictionaries
• associative arrays
2016 Winter
public interface Map {
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
void putAll(Map map);
void clear();
Set keySet();
Collection values();
}
Basic ops
Bulk ops
Collection
views
2016 Winter
• Map is an interface; you can't say new Map()
• There are two implementations:
– java.util.HashMap is best for most purposes
• Preferred:
Map<Key,Value> m = new HashMap<Key,Value> ();
• Not:
HashMap<Key,Value> m = new HashMap<Key,Value> ();
2016 Winter
Map<String,String> m = new HashMap<String,String> ();
grades.put("Martin", "A");
grades.put("Nelson", "F");
grades.put(“Alex", "B");
// What grade did they get?
System.out.println(
grades.get("Nelson"));
System.out.println(
grades.get("Martin"));
grades.put("Nelson", "W");
grades.remove("Martin");
System.out.println(
grades.get("Nelson"));
System.out.println(
grades.get("Martin"));
HashMap
0
2
5
HashMap grades
HashMapEntry
"Martin" "A"
HashMapEntry
"Nelson" "F"
HashMapEntry
“Alex" "B"
2016 Winter
public class Example {
public static void main(String[] args){
Map m = new HashMap();
m.put("Newton", new Integer(1642));
m.put("Darwin", new Integer(1809));
System.out.println(m);
}
}
Output:
{Darwin=1809, Newton=1642}
2016 Winter
• public Object get(Object key)
– returns the value at the specified key, or null if the key is
not in the map (constant time)
• public boolean containsKey(Object key)
– returns true if the map contains a mapping for the
specified key (constant time)
• public boolean containsValue(Object
val)
– returns true if the map contains the specified object as a
value
– this method is not constant-time O(1) ... why not?
2016 Winter
• A map itself is not regarded as a collection
– Map does not implement Collection interface
– although, in theory, it could be seen as a
collection of pairs, or a relation in discrete math
terminology
• Instead collection views of a map may be
obtained
– Set of its keys
– Collection of its values (not a set... why?)
2016 Winter
• Map interface has no iterator method; you can’t get an
Iterator directly
• must first call either
– keySet() returns a Set of all the keys in this Map
– values() returns a Collection of all the values in this
Map
• then call iterator() on the key set or values. Examples:
Iterator keyItr = grades.keySet().iterator();
Iterator elementItr = grades.values().iterator();
– If you really want the keys or element values in a more familiar
collection such as an ArrayList, use the ArrayList constructor
that takes a Collection as its argument
ArrayList elements = new
ArrayList(grades.values());
2016 Winter
Java Tutorial Lab 8

More Related Content

What's hot

Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
Knolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaKnolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaAyush Mishra
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for HaskellMartin Ockajak
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersMartin Ockajak
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On RandomnessRanel Padon
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingRanel Padon
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 

What's hot (20)

Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
Scala functions
Scala functionsScala functions
Scala functions
 
Knolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaKnolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in Scala
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Templates
TemplatesTemplates
Templates
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
30csharp
30csharp30csharp
30csharp
 
Java generics
Java genericsJava generics
Java generics
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Scala
ScalaScala
Scala
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator Overloading
 
Functional object
Functional objectFunctional object
Functional object
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 

Viewers also liked

Java Tutorial Lab 9
Java Tutorial Lab 9Java Tutorial Lab 9
Java Tutorial Lab 9Berk Soysal
 
Self Evaluation Test
Self Evaluation Test Self Evaluation Test
Self Evaluation Test Berk Soysal
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2Berk Soysal
 
Java Tutorial Lab 7
Java Tutorial Lab 7Java Tutorial Lab 7
Java Tutorial Lab 7Berk Soysal
 
Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4Berk Soysal
 
Java Tutorial Lab 1
Java Tutorial Lab 1Java Tutorial Lab 1
Java Tutorial Lab 1Berk Soysal
 

Viewers also liked (7)

Java Tutorial Lab 9
Java Tutorial Lab 9Java Tutorial Lab 9
Java Tutorial Lab 9
 
Self Evaluation Test
Self Evaluation Test Self Evaluation Test
Self Evaluation Test
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2
 
Java Tutorial Lab 7
Java Tutorial Lab 7Java Tutorial Lab 7
Java Tutorial Lab 7
 
Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4
 
Java Tutorial Lab 1
Java Tutorial Lab 1Java Tutorial Lab 1
Java Tutorial Lab 1
 

Similar to Java Tutorial Lab 8

File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfConint29
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manualChandrapriya Jayabal
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfJUSTSTYLISH3B2MOHALI
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfJkPoppy
 
Use the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docxUse the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docxdickonsondorris
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
Data Structure and Algorithms Stacks
Data Structure and Algorithms StacksData Structure and Algorithms Stacks
Data Structure and Algorithms StacksManishPrajapati78
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdfkamdinrossihoungma74
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 

Similar to Java Tutorial Lab 8 (20)

File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdf
 
7 stacksqueues
7 stacksqueues7 stacksqueues
7 stacksqueues
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
 
Use the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docxUse the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docx
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Data Structure and Algorithms Stacks
Data Structure and Algorithms StacksData Structure and Algorithms Stacks
Data Structure and Algorithms Stacks
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 

Java Tutorial Lab 8

  • 1. LAB #8 Prepared by: Berk Soysal 2016 Winter
  • 2.  Often, you will want to cycle through the elements in a collection. For example, you might want to display each element or remove an element.  The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. 2016 Winter
  • 3. Iterator ListIterator Unidirectional (forward iteration) Has only next() Bidirectional (forward and backward iteration) Has next() and previous() Map, List, Set implemented Objects List implemented Objects only remove() only add(), remove() Cannot determine current position of the iterator Can determine the current position of the iterator 2016 Winter
  • 4.  The Iterator interface specifies 3 methods: boolean hasNext() //returns true if this iteration has more elements E next() //returns the next element in this iteration //pre: hastNext() void remove() /*Removes from the underlying collection the last element returned by the iterator. pre: This method can be called only once per call to next. After calling, must call next again before calling remove again. */ 2016 Winter
  • 5. Imagine a fence made up of fence posts and rail sections. fenceposts rails 2016 Winter
  • 6.  The iterator lives on the fence posts  The data in the collection are the rails  Iterator created at the far left post  As long as a rail exists to the right of the Iterator, hasNext() is true iterator object 2016 Winter
  • 7. ArrayList<String> names =new ArrayList<String>(); names.add(“Alex”); names.add(“Liz”); names.add(“Tim”); names.add(“Jack”); Iterator<String> it = names.iterator(); int i = 0; iterator object “Alex” “Liz” “Tim” “Jack” 2016 Winter
  • 8. “Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 1, prints out Alex  first call to next moves iterator to next post and returns “Alex” 2016 Winter
  • 9. “Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 2, prints out Liz 2016 Winter
  • 10. “Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 3, prints out Tim 2016 Winter
  • 11. “Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 4, prints out Jack 2016 Winter
  • 12. “Alex” “Liz” “Tim” “Jack” while( it.hasNext() ) { i++; System.out.println( it.next() ); } // while loop stops since call to hasNext returns false 2016 Winter
  • 13.  An Iterator can be used to remove things from the Collection  Can only be called once per call to next() public void removeWordsOfLength(int len) { Iterator<String> it = myList.iterator(); while( it.hasNext() ) { String temp = it.next(); if(temp.length() == len) it.remove(); } } // myList = [“dogs”, “cat”, “hats”, “bikes”] // resulting list after removeWordsOfLength(3) ? 2016 Winter
  • 14.  In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java.  The class written within is called the nested class, and the class that holds the inner class is called the outer class. class OuterClass{ class InnerClass{ } }  Inner classes are a security mechanism in Java. 2016 Winter
  • 15.  We know a regular class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. 2016 Winter
  • 16. You are provided an almost complete implementation of a class. Complete the implementation of the class BitList. public BitList( String s ); creates a list of bits representing the input string s. The given string, s, must be a string of 0s and 1s, otherwise the constructor must throw an exception of type IllegalArgumentException. This constructor initializes the new BitList instance to represent the value in the string. Each character in the string represents one bit of the list, with the rightmost character in the string being the low order bit. For example, given the string “1010111” the constructor should initialize the new BitList to include this list of bits: -> 1 -> 1 -> 1 -> 0 -> 1 -> 0 -> 1 2016 Winter
  • 17. Use the class called Iterative. Implement the methods below. Your solutions must be iterative (i.e. uses iterators). 2016 Winter
  • 20. • Map: an unordered collection that associates a collection of element values with a set of keys so that elements they can be found very quickly (O(1)!) – Each key can appear at most once (no duplicate keys) – A key maps to at most one value – the main operations: • put(key, value) "Map this key to that value." • get(key) "What value, if any, does this key map to?" – maps are also called: • hashes or hash tables • dictionaries • associative arrays 2016 Winter
  • 21. public interface Map { Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); void putAll(Map map); void clear(); Set keySet(); Collection values(); } Basic ops Bulk ops Collection views 2016 Winter
  • 22. • Map is an interface; you can't say new Map() • There are two implementations: – java.util.HashMap is best for most purposes • Preferred: Map<Key,Value> m = new HashMap<Key,Value> (); • Not: HashMap<Key,Value> m = new HashMap<Key,Value> (); 2016 Winter
  • 23. Map<String,String> m = new HashMap<String,String> (); grades.put("Martin", "A"); grades.put("Nelson", "F"); grades.put(“Alex", "B"); // What grade did they get? System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); grades.put("Nelson", "W"); grades.remove("Martin"); System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); HashMap 0 2 5 HashMap grades HashMapEntry "Martin" "A" HashMapEntry "Nelson" "F" HashMapEntry “Alex" "B" 2016 Winter
  • 24. public class Example { public static void main(String[] args){ Map m = new HashMap(); m.put("Newton", new Integer(1642)); m.put("Darwin", new Integer(1809)); System.out.println(m); } } Output: {Darwin=1809, Newton=1642} 2016 Winter
  • 25. • public Object get(Object key) – returns the value at the specified key, or null if the key is not in the map (constant time) • public boolean containsKey(Object key) – returns true if the map contains a mapping for the specified key (constant time) • public boolean containsValue(Object val) – returns true if the map contains the specified object as a value – this method is not constant-time O(1) ... why not? 2016 Winter
  • 26. • A map itself is not regarded as a collection – Map does not implement Collection interface – although, in theory, it could be seen as a collection of pairs, or a relation in discrete math terminology • Instead collection views of a map may be obtained – Set of its keys – Collection of its values (not a set... why?) 2016 Winter
  • 27. • Map interface has no iterator method; you can’t get an Iterator directly • must first call either – keySet() returns a Set of all the keys in this Map – values() returns a Collection of all the values in this Map • then call iterator() on the key set or values. Examples: Iterator keyItr = grades.keySet().iterator(); Iterator elementItr = grades.values().iterator(); – If you really want the keys or element values in a more familiar collection such as an ArrayList, use the ArrayList constructor that takes a Collection as its argument ArrayList elements = new ArrayList(grades.values()); 2016 Winter