SlideShare una empresa de Scribd logo
1 de 20
Lecture 7
Collections




       Object Oriented Programming
        Eastern University, Dhaka
                Md. Raihan Kibria
An example
 import java.util.ArrayList;

 public class CollectionsDemo1 {

     public static void main(String[] args) {

         ArrayList arrayList = new ArrayList();
         for (int i=0; i<10; i++)
           arrayList.add(new Integer(i));

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

         }

     }
 }



ArrayList is a collection. The above
example prints 0 to 9
What else can we do with ArrayList
import java.util.ArrayList;

public class CollectionsDemo1 {

    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();
        for (int i=0; i<10; i++)
          arrayList.add(new Integer(i));

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

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

}

The last segment prints 1 to 9 because we
have removed the object at index 0
Can we keep any kind of objects in
          a collection?
   public class CollectionsDemo2 {

       public static void main(String[] args) {

           ArrayList list = new ArrayList();
           for (int i=0; i<4; i++)
             list.add(new JButton(String.valueOf(i)));

           JFrame jframe = new JFrame();
           jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           jframe.setBounds(0, 0, 300, 200);
           jframe.getContentPane().setLayout(new FlowLayout());
           for (int i=0; i<list.size(); i++){
             jframe.getContentPane().add((JButton)list.get(i));
           }
           jframe.setVisible(true);
       }
   }


We have added JButton objects into the ArrayList list
The output
Can't we have plain array of
                objects in java?
  public class CollectionsDemoWithout {

      public static void main(String[] args) {
        JButton[] myButtons = new JButton[]{new Jbutton("0")
          ,new JButton("1"), new JButton("2"), new JButton("3"), };
        JFrame jframe = new JFrame();
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setBounds(0, 0, 300, 200);
        jframe.getContentPane().setLayout(new FlowLayout());
        for (int i=0; i<myButtons.length; i++){
          jframe.getContentPane().add(myButtons[i]);
        }
        jframe.setVisible(true);
      }
  }




Yes we can
The output
Difference between array and an
                Arraylist

•
    An array is of fixed size
•
    An ArrayList can grow and reduce in size
•
    Any collection can grow and reduce in size
    but arrays cannot
•
    i.e. ArrayList list = new ArrayList();
       list.add(new Integer()); //is allowed
•
    But this is not allowed:
       Integer[] intArr = new Integer[3];
       intArr.add(new Integer());
Question




Which one is flexible: Array or ArrayList?
Which one is faster: Array or ArrayList?
Answer




ArrayList is more flexible since we can
dynamically change its dimension or size
Array is faster because JVM needs to do less
work to maintain the size (size is pre-known)
What else is there under
           collections



HashSet
TreeSet
Queue
HashMap
etc.
An introduction to Interfaces

An example of interface:

Interface GiveText{
  String GiveText();
}
public class CollectionsDemoInterface {
  public static void printText(GiveSomething giveSomething){
    System.out.println(giveSomething.giveText());
  }
  public static void main(String[] args) {
    CollectionsDemoInterface.printText(new X());
    CollectionsDemoInterface.printText(new Y());
    CollectionsDemoInterface.printText(new Z());
  }
}

interface GiveSomething{
  String giveText();
}

class X implements GiveSomething{
  public String giveText() {
    return "Orange";
  }
}

class Y implements GiveSomething{
  public String giveText() {
    return "Apple";
  }
}

class Z implements GiveSomething{
  public String giveText() {
    return "Grapes";
  }
}
Output




Orange
Apple
Grapes
Why do we need Interfaces


Sometimes we do not know what our actual
object is but we still want some operation
done; for example, some method of that object
called
The main reason we do not know about the
actual object beforehand (while coding) is that
someone else is developing that object
Why do we need Interfaces
For example, we have two types of list:
ArrayList and LinkedList. These two classes
were developed by two different teams;
however, the integrator developer has defined
a common interface List

Interface List contains methods like
add(Object o), add(int index, Object o)

Therefore, both ArrayList and LinkedList has
those methods
Example of List interface
List myList = new ArrayList();
List yourList = new LinkedList();

Please note the left side of the assignments
contains List interface and the right side the
actual object.

Since add(Object o) is defined in List interface
we can do both
    myList.add(new Integer(1));
    yourList.add(new Integer(1)));
A list that contains different types
                 of objects
public class CollectionsDemoInterface {
  public static void printText(GiveSomething giveSomething){
    System.out.println(giveSomething.giveText());
  }
  public static void main(String[] args) {
    List<GiveSomething>myGenericList = new ArrayList<GiveSomething>();
    myGenericList.add(new X());
    myGenericList.add(new Y());
    myGenericList.add(new Z());
  }
}




       See next page for the remaining
       code
interface GiveSomething{
String giveText();
}

class X implements GiveSomething{
public String giveText() {
return "Orange";
}
}

class Y implements GiveSomething{
public String giveText() {
return "Apple";
}
}

class Z implements GiveSomething{
public String giveText() {
return "Grapes";
}
}
for (GiveSomething g : myGenericList)
   System.out.println(g.giveText());




 Will print:

 Orange
 Apple
 Grape

Más contenido relacionado

La actualidad más candente (20)

The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
 
List in Python
List in PythonList in Python
List in Python
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
 
Lists
ListsLists
Lists
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
1. python
1. python1. python
1. python
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Array
ArrayArray
Array
 
Python list
Python listPython list
Python list
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 

Similar a Oop lecture7

Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresArthik Daniel
 
I only need help with four methods in the EmployeeManager class the .pdf
I only need help with four methods in the EmployeeManager class the .pdfI only need help with four methods in the EmployeeManager class the .pdf
I only need help with four methods in the EmployeeManager class the .pdfarpitcomputronics
 
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfWhy following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfgopalk44
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
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
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 

Similar a Oop lecture7 (20)

Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
 
Array list
Array listArray list
Array list
 
Aj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructuresAj unit2 notesjavadatastructures
Aj unit2 notesjavadatastructures
 
Collections
CollectionsCollections
Collections
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
I only need help with four methods in the EmployeeManager class the .pdf
I only need help with four methods in the EmployeeManager class the .pdfI only need help with four methods in the EmployeeManager class the .pdf
I only need help with four methods in the EmployeeManager class the .pdf
 
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdfWhy following sort does not work (It does not sort last 2 - 3 numbe.pdf
Why following sort does not work (It does not sort last 2 - 3 numbe.pdf
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
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
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
 
Presentation1
Presentation1Presentation1
Presentation1
 
07 java collection
07 java collection07 java collection
07 java collection
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Groovy
GroovyGroovy
Groovy
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 

Más de Shahriar Robbani (13)

Group111
Group111Group111
Group111
 
SQL
SQLSQL
SQL
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
 
Oop lecture4
Oop lecture4Oop lecture4
Oop lecture4
 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
 
Oop lecture9
Oop lecture9Oop lecture9
Oop lecture9
 
Oop lecture5
Oop lecture5Oop lecture5
Oop lecture5
 
Oop lecture3
Oop lecture3Oop lecture3
Oop lecture3
 
Oop lecture1
Oop lecture1Oop lecture1
Oop lecture1
 
Oop lecture6
Oop lecture6Oop lecture6
Oop lecture6
 

Último

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 

Último (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 

Oop lecture7

  • 1. Lecture 7 Collections Object Oriented Programming Eastern University, Dhaka Md. Raihan Kibria
  • 2. An example import java.util.ArrayList; public class CollectionsDemo1 { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); for (int i=0; i<10; i++) arrayList.add(new Integer(i)); for (int i=0; i<arrayList.size(); i++) System.out.println(arrayList.get(i)); } } } ArrayList is a collection. The above example prints 0 to 9
  • 3. What else can we do with ArrayList import java.util.ArrayList; public class CollectionsDemo1 { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); for (int i=0; i<10; i++) arrayList.add(new Integer(i)); for (int i=0; i<arrayList.size(); i++) System.out.println(arrayList.get(i)); arrayList.remove(0); for (int i=0; i<arrayList.size(); i++) System.out.println(arrayList.get(i)); } } The last segment prints 1 to 9 because we have removed the object at index 0
  • 4. Can we keep any kind of objects in a collection? public class CollectionsDemo2 { public static void main(String[] args) { ArrayList list = new ArrayList(); for (int i=0; i<4; i++) list.add(new JButton(String.valueOf(i))); JFrame jframe = new JFrame(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setBounds(0, 0, 300, 200); jframe.getContentPane().setLayout(new FlowLayout()); for (int i=0; i<list.size(); i++){ jframe.getContentPane().add((JButton)list.get(i)); } jframe.setVisible(true); } } We have added JButton objects into the ArrayList list
  • 6. Can't we have plain array of objects in java? public class CollectionsDemoWithout { public static void main(String[] args) { JButton[] myButtons = new JButton[]{new Jbutton("0") ,new JButton("1"), new JButton("2"), new JButton("3"), }; JFrame jframe = new JFrame(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setBounds(0, 0, 300, 200); jframe.getContentPane().setLayout(new FlowLayout()); for (int i=0; i<myButtons.length; i++){ jframe.getContentPane().add(myButtons[i]); } jframe.setVisible(true); } } Yes we can
  • 8. Difference between array and an Arraylist • An array is of fixed size • An ArrayList can grow and reduce in size • Any collection can grow and reduce in size but arrays cannot • i.e. ArrayList list = new ArrayList(); list.add(new Integer()); //is allowed • But this is not allowed: Integer[] intArr = new Integer[3]; intArr.add(new Integer());
  • 9. Question Which one is flexible: Array or ArrayList? Which one is faster: Array or ArrayList?
  • 10. Answer ArrayList is more flexible since we can dynamically change its dimension or size Array is faster because JVM needs to do less work to maintain the size (size is pre-known)
  • 11. What else is there under collections HashSet TreeSet Queue HashMap etc.
  • 12. An introduction to Interfaces An example of interface: Interface GiveText{ String GiveText(); }
  • 13. public class CollectionsDemoInterface { public static void printText(GiveSomething giveSomething){ System.out.println(giveSomething.giveText()); } public static void main(String[] args) { CollectionsDemoInterface.printText(new X()); CollectionsDemoInterface.printText(new Y()); CollectionsDemoInterface.printText(new Z()); } } interface GiveSomething{ String giveText(); } class X implements GiveSomething{ public String giveText() { return "Orange"; } } class Y implements GiveSomething{ public String giveText() { return "Apple"; } } class Z implements GiveSomething{ public String giveText() { return "Grapes"; } }
  • 15. Why do we need Interfaces Sometimes we do not know what our actual object is but we still want some operation done; for example, some method of that object called The main reason we do not know about the actual object beforehand (while coding) is that someone else is developing that object
  • 16. Why do we need Interfaces For example, we have two types of list: ArrayList and LinkedList. These two classes were developed by two different teams; however, the integrator developer has defined a common interface List Interface List contains methods like add(Object o), add(int index, Object o) Therefore, both ArrayList and LinkedList has those methods
  • 17. Example of List interface List myList = new ArrayList(); List yourList = new LinkedList(); Please note the left side of the assignments contains List interface and the right side the actual object. Since add(Object o) is defined in List interface we can do both myList.add(new Integer(1)); yourList.add(new Integer(1)));
  • 18. A list that contains different types of objects public class CollectionsDemoInterface { public static void printText(GiveSomething giveSomething){ System.out.println(giveSomething.giveText()); } public static void main(String[] args) { List<GiveSomething>myGenericList = new ArrayList<GiveSomething>(); myGenericList.add(new X()); myGenericList.add(new Y()); myGenericList.add(new Z()); } } See next page for the remaining code
  • 19. interface GiveSomething{ String giveText(); } class X implements GiveSomething{ public String giveText() { return "Orange"; } } class Y implements GiveSomething{ public String giveText() { return "Apple"; } } class Z implements GiveSomething{ public String giveText() { return "Grapes"; } }
  • 20. for (GiveSomething g : myGenericList) System.out.println(g.giveText()); Will print: Orange Apple Grape