SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus 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
 

Dernier

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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
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
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
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
 
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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
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
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 

Dernier (20)

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
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
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
 
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 ...
 
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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
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...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

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