SlideShare una empresa de Scribd logo
1 de 18
Lecture 13
Iteration in Java




           Object Oriented Programming
            Eastern University, Dhaka
                    Md. Raihan Kibria
Simple c-style iteration

public class IterationDemo {

    public static void main(String[] args) {
      List<String>lst = new ArrayList<String>();
      lst.add("One");
      lst.add("Two");
      lst.add("Three");

        for (int i=0; i<lst.size(); i++)
            System.out.println(lst.get(i));

    }
}




        Output:
        One
        Two
        Three
More iterators
 //more eye-friendly iteration
 for (String s : lst)
   System.out.println(s);


 Gives the same output


Most generic iteration—using Iterator
 Iterator<String>it = lst.iterator();
 while (it.hasNext())
   System.out.println(it.next());

 Gives the same output
Iterating over a set
Set<String>s = new HashSet<String>();
s.add("One");
s.add("Two");
s.add("Three");

Iterator<String>it = lst.iterator();
while (it.hasNext())
  System.out.println(it.next());

Gives the same output:
One
Two
Three
Iterating over a map
Map<String, String>map = new HashMap<String, String>();
map.put("One", "111111");
map.put("Two", "222222");
map.put("Three", "333333");

Iterator<Map.Entry<String, String>>it = map.entrySet().iterator();
while (it.hasNext()){
  Map.Entry<String, String>entry = it.next();
  System.out.println(entry.getKey() + "--" + entry.getValue());
}




            Output:

            Three--333333
            One--111111
            Two--222222
Remember old style iteration still
       works for arrays
 String[] str = new String[]{"One", "Two", "Three"};
 for (int i=0; i<str.length; i++)
   System.out.println(str[i]);

     Output:
     One
     Two
     Three



String[] str = new String[]{"One", "Two", "Three"};

for (String s : str)
  System.out.println(s);
       Output:
       One
       Two
       Three
Some common methods present in
         all objects
toString()
equals()
hashCode()
finalize()
toString()
public class Student {
  int id;
  String name;

     public Student(int id, String name) {
       super();
       this.id = id;
       this.name = name;
     }

     public String toString(){
       return this.id + "--" + this.name;
 }
}


public static void main(String[] args){
    Student student = new Student(3, "Joe");
    System.out.println(student);
}

Output:
3--Joe
Another toString() demo
List<Student>stus = new ArrayList<Student>();
Student st = new Student(1, "John");
stus.add(st);
stus.add(st);
System.out.println("Printing list: ");
for (Student s: stus)
    System.out.println(s);


     Output:

     Printing list:
     1--John
     1--John
hashCode() demo with equals()
public class HashCodeDemo {

    public static class Student {
      int id;
      String name;

    public Student(int id, String name) {
      super();
      this.id = id;
      this.name = name;
    }

    public String toString() {
      return this.id + "--" + this.name;
    }

     /*      public boolean equals(Object obj) {
     Student arg = (Student) obj;
     return this.id == arg.id;
     }*/

    public int hashCode() {
      return this.id;
    }
}
public static void main(String[] args) {
      Map<Student, String> map = new HashMap<Student, String>();
      map.put(new Student(1, "John"), null);
      map.put(new Student(1, "John"), null);
      map.put(new Student(2, "John"), null);
      System.out.println(map.size());

      Iterator<Map.Entry<Student, String>> it1 = map.entrySet().iterator();
      System.out.println("Printing map: ");
      while (it1.hasNext())
        System.out.println(it1.next());
      }
}



    Output:                 Now we uncomment the equals() method in the
    3                       previous slide:
    Printing map:
    1--John=null            Output:
    1--John=null            2
    2--John=null            Printing map:
                            1--John=null
                            2--John=null

      Explanation: hashCode merely specifies a slot;
      equals() helps put the object in the slot
equals() method
 Two objects are equal if their equals() method returns
  true. Demo:
public class Student {
    int id;
    String name;

    public Student(int id, String name) {
      super();
      this.id = id;
      this.name = name;
    }

    public String toString(){
      return this.id + "--" + this.name;
    }

    public int hashCode() {
      return this.id;
    }

    public boolean equals(Object obj) {
      Student s = (Student)obj;
      if (s.id == this.id)
          return true;
      return false;
    }
equals() continued
 System.out.println(st.equals(st2));
 System.out.println(st==st2);




Output:

true
false




In java “==” operator is not same as “equals()”
finalize()
   What is garbage collection?
   In C/C++ the programmer can get a chunk
    of program using malloc() and can dispose
    memory using memfree()
   Having programmer free will at memory
    management resulted in memory leaks in
    many C programs
   Java will not let programmer directly
    acquiring memory.
   Rather JVM manages memory
Finalize() (c..)
•
    When an object is de-referenced, the object
    is automatically removed from the memory
    by JVM.
•
    Whenever, an object is removed its finalize()
    method is called
•
    Garbage collection is automatically
    scheduled by the JVM
•
    However, a programmer can trigger a
    garbage collection by calling System.gc()
•
    Example in the next page:
Finalize() (c..)
public class AnObject {

    protected void finalize() throws Throwable {
      super.finalize();
      System.out.println("Finalize method is called");
    }

    public static void main(String[] args){
      new AnObject();
    }
}


    Output:
Finalize() (c..)
public class AnObject {

    protected void finalize() throws Throwable {
      super.finalize();
      System.out.println("Finalize method is called");
    }

    public static void main(String[] args){
      new AnObject();
      System.gc();
    }
}




Output:
Finalize method is called
Garbage collection formally
             defined
Garbage collection is a mechanism provided
 by Java Virtual Machine to reclaim heap
 space from objects which are eligible for
 Garbage collection

Más contenido relacionado

La actualidad más candente

Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbookManusha Dilan
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data ScienceMike Anderson
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88Mahmoud Samir Fayed
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Sciencehenrygarner
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Namgee Lee
 
Machine Learning Live
Machine Learning LiveMachine Learning Live
Machine Learning LiveMike Anderson
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional ProgrammingDmitry Buzdin
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat SheetKarlijn Willems
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia岳華 杜
 

La actualidad más candente (20)

Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
 
Java practical
Java practicalJava practical
Java practical
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
 
Clojure class
Clojure classClojure class
Clojure class
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
JDBC Core Concept
JDBC Core ConceptJDBC Core Concept
JDBC Core Concept
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Machine Learning Live
Machine Learning LiveMachine Learning Live
Machine Learning Live
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Javascript
JavascriptJavascript
Javascript
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 

Destacado (9)

Calendario portada
Calendario portadaCalendario portada
Calendario portada
 
Oop lecture6
Oop lecture6Oop lecture6
Oop lecture6
 
Oop lecture1
Oop lecture1Oop lecture1
Oop lecture1
 
Cwgd
CwgdCwgd
Cwgd
 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
 
Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
 
Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
 
Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]
 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
 

Similar a Oop lecture9 13

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
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
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 
Write a program that reads a graph from a file and determines whether.docx
 Write a program that reads a graph from a file and determines whether.docx Write a program that reads a graph from a file and determines whether.docx
Write a program that reads a graph from a file and determines whether.docxajoy21
 
Java programs
Java programsJava programs
Java programsjojeph
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 

Similar a Oop lecture9 13 (20)

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Utility.ppt
Utility.pptUtility.ppt
Utility.ppt
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
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
 
Java programs
Java programsJava programs
Java programs
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Java programs
Java programsJava programs
Java programs
 
Write a program that reads a graph from a file and determines whether.docx
 Write a program that reads a graph from a file and determines whether.docx Write a program that reads a graph from a file and determines whether.docx
Write a program that reads a graph from a file and determines whether.docx
 
Java programs
Java programsJava programs
Java programs
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 

Más de Shahriar Robbani (8)

Group111
Group111Group111
Group111
 
SQL
SQLSQL
SQL
 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
 
Oop lecture4
Oop lecture4Oop lecture4
Oop lecture4
 
Oop lecture9
Oop lecture9Oop lecture9
Oop lecture9
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
 
Oop lecture5
Oop lecture5Oop lecture5
Oop lecture5
 
Oop lecture3
Oop lecture3Oop lecture3
Oop lecture3
 

Último

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 

Último (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 

Oop lecture9 13

  • 1. Lecture 13 Iteration in Java Object Oriented Programming Eastern University, Dhaka Md. Raihan Kibria
  • 2. Simple c-style iteration public class IterationDemo { public static void main(String[] args) { List<String>lst = new ArrayList<String>(); lst.add("One"); lst.add("Two"); lst.add("Three"); for (int i=0; i<lst.size(); i++) System.out.println(lst.get(i)); } } Output: One Two Three
  • 3. More iterators //more eye-friendly iteration for (String s : lst) System.out.println(s); Gives the same output Most generic iteration—using Iterator Iterator<String>it = lst.iterator(); while (it.hasNext()) System.out.println(it.next()); Gives the same output
  • 4. Iterating over a set Set<String>s = new HashSet<String>(); s.add("One"); s.add("Two"); s.add("Three"); Iterator<String>it = lst.iterator(); while (it.hasNext()) System.out.println(it.next()); Gives the same output: One Two Three
  • 5. Iterating over a map Map<String, String>map = new HashMap<String, String>(); map.put("One", "111111"); map.put("Two", "222222"); map.put("Three", "333333"); Iterator<Map.Entry<String, String>>it = map.entrySet().iterator(); while (it.hasNext()){ Map.Entry<String, String>entry = it.next(); System.out.println(entry.getKey() + "--" + entry.getValue()); } Output: Three--333333 One--111111 Two--222222
  • 6. Remember old style iteration still works for arrays String[] str = new String[]{"One", "Two", "Three"}; for (int i=0; i<str.length; i++) System.out.println(str[i]); Output: One Two Three String[] str = new String[]{"One", "Two", "Three"}; for (String s : str) System.out.println(s); Output: One Two Three
  • 7. Some common methods present in all objects toString() equals() hashCode() finalize()
  • 8. toString() public class Student { int id; String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } public String toString(){ return this.id + "--" + this.name; } } public static void main(String[] args){ Student student = new Student(3, "Joe"); System.out.println(student); } Output: 3--Joe
  • 9. Another toString() demo List<Student>stus = new ArrayList<Student>(); Student st = new Student(1, "John"); stus.add(st); stus.add(st); System.out.println("Printing list: "); for (Student s: stus) System.out.println(s); Output: Printing list: 1--John 1--John
  • 10. hashCode() demo with equals() public class HashCodeDemo { public static class Student { int id; String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } public String toString() { return this.id + "--" + this.name; } /* public boolean equals(Object obj) { Student arg = (Student) obj; return this.id == arg.id; }*/ public int hashCode() { return this.id; } }
  • 11. public static void main(String[] args) { Map<Student, String> map = new HashMap<Student, String>(); map.put(new Student(1, "John"), null); map.put(new Student(1, "John"), null); map.put(new Student(2, "John"), null); System.out.println(map.size()); Iterator<Map.Entry<Student, String>> it1 = map.entrySet().iterator(); System.out.println("Printing map: "); while (it1.hasNext()) System.out.println(it1.next()); } } Output: Now we uncomment the equals() method in the 3 previous slide: Printing map: 1--John=null Output: 1--John=null 2 2--John=null Printing map: 1--John=null 2--John=null Explanation: hashCode merely specifies a slot; equals() helps put the object in the slot
  • 12. equals() method  Two objects are equal if their equals() method returns true. Demo: public class Student { int id; String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } public String toString(){ return this.id + "--" + this.name; } public int hashCode() { return this.id; } public boolean equals(Object obj) { Student s = (Student)obj; if (s.id == this.id) return true; return false; }
  • 13. equals() continued System.out.println(st.equals(st2)); System.out.println(st==st2); Output: true false In java “==” operator is not same as “equals()”
  • 14. finalize()  What is garbage collection?  In C/C++ the programmer can get a chunk of program using malloc() and can dispose memory using memfree()  Having programmer free will at memory management resulted in memory leaks in many C programs  Java will not let programmer directly acquiring memory.  Rather JVM manages memory
  • 15. Finalize() (c..) • When an object is de-referenced, the object is automatically removed from the memory by JVM. • Whenever, an object is removed its finalize() method is called • Garbage collection is automatically scheduled by the JVM • However, a programmer can trigger a garbage collection by calling System.gc() • Example in the next page:
  • 16. Finalize() (c..) public class AnObject { protected void finalize() throws Throwable { super.finalize(); System.out.println("Finalize method is called"); } public static void main(String[] args){ new AnObject(); } } Output:
  • 17. Finalize() (c..) public class AnObject { protected void finalize() throws Throwable { super.finalize(); System.out.println("Finalize method is called"); } public static void main(String[] args){ new AnObject(); System.gc(); } } Output: Finalize method is called
  • 18. Garbage collection formally defined Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection