SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados (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
 

Semelhante 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
 

Semelhante 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
 

Mais 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

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
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
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
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 

Último (20)

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...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
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
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

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