SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Kürzlich hochgeladen

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
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
 
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
 
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
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
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
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
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 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
 
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
 
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
 

Kürzlich hochgeladen (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
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
 
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
 
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
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
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
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
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 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.
 
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
 
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
 

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