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

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 

Último (20)

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 

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