SlideShare una empresa de Scribd logo
1 de 39
  Text-Based Application & Collection API
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Varargs With JDK 5.0 Java has included a feature that implifies the  creation of methods, that need to take variable number of arguments. This feature is called varargs and it short form for variable length  arguments. Prior to JDK5, variable length argument could be handled using arrays. Example  PassArray With variable length arguments A variable length argument is specified by three periods(…) To write a method using varargs static void vaTest (int …v)  Example  VarArgs
v is operated  as an array …  syntax simply tell the compiler that a variable number of arguments will be used. A method can have normal parameters along with variable length  parameters, however the variable length parameter must be last  parameter declared by the method. int doit(int a, int b, double c, int …vals) Overloading Vararg Methods Example  VarArgs2
String   is a sequence of characters. But, unlike many  other languages that implement strings as character arrays,  Java implements strings as objects of type  String . * Once a  String  object has been created, you cannot  change the characters that comprise that string. * Each time you need an altered version of an  existing string, a new  String  object is created that contains the modifications. The original string is  left unchanged.
* For those cases in which a modifiable string is desired,  there is a companion class to  String  called  StringBuffer ,  whose objects contain strings that can be modified after  they are created. * Both the  String  and  StringBuffer  classes are declared  final * The length of a string is the number of characters that it  contains. To obtain this value, call the  length( )  method, char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length());
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
// equals() vs == class EqualsNotEqualTo { public static void main(String args[]) { String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + "  " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + "  " + (s1 == s2)); } }
[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The core collection interfaces encapsulate different  types of collections, These interfaces allow collections to be manipulated independently of the details of  their representation.  A Set is a special kind of Collection.  A SortedSet is a special kind of Set.
The Collection interface is the least common  denominator that all collections implement  * The Java platform doesn't provide any direct  implementations of this interface but provides  implementations of more specific subinterfaces, such  as Set and List. Set  — a collection that cannot contain  duplicate   elements. This interface models the mathematical set  abstraction and is used to represent Sets.
List  — an ordered collection (sometimes called a  sequence ). Lists can contain duplicate elements. The user of a List  generally has precise control over where in the list each  element is inserted and can access elements by their integer  index (position). Queue  — a collection used to hold multiple elements  prior to processing. Besides basic Collection operations,  a Queue provides additional insertion, extraction,  and inspection operations. Map  — an object that maps keys to values. A Map cannot  contain duplicate keys: each key can map to at most one  value.
SortedSet  — a Set that maintains its elements in ascending  order. Sorted sets are used for naturally ordered sets. SortedMap  — a Map that maintains its mappings in  ascending key order. Implementation The classes that implement these interfaces are  listed below: Set  HashSet  TreeSet  LinkedHashSet List  Vector  ArrayList  LinkedList Map  HashMap  HashTable  TreeMap  LinkedHashMap SortedSet  TreeSet SortedMap   TreeMap
Interface and class hierarchy of collections
 
The ArrayList Class The ArrayList class extends AbstractList and implements the List  interface.  * ArrayList supports dynamic arrays that can grow as needed. * An  ArrayList  is a variable-length array of object references. * Since this implementation use an array to store the elements  of the list, so access to an element using an index is very fast. Example  ArrayListDemo.java Example  ArrayListToArray.java For obtaining an Array from an ArrayList.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Vector public class Vector extends AbstractList implements List. Vector is synchronized.  Vector constructors: Vector( ) The first form creates a default vector,which has an initial  size of 10.  Vector(int initialCapacity)   Constructs an empty vector with the specified initial  capacity and with its capacity increment equal to zero.  Vector(int initialCapacity, int capacityIncrement)              Constructs an empty vector with the specified initial  capacity and capacity increment.
Vector use an array to store the elements of the list; so  access to any element using an index is very fast.  Example  VectorDemo.java
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The TreeSet Class * Duplicate elements are not accepted. * TreeSet provides an implementation of the SortedSet  interface that uses a tree for storage. * This class guarantees that the sorted set will be in  ascending element order  * This implementation provides guaranteed log(n)  time cost for the basic operations . * Access and retrieval times are quite fast,which  makes  TreeSet  an excellent choice when storing large  amounts of sorted information that must be found quickly. * This implementation is not synchronized  *  The entries can be sorted using the Comparable interface.  Example  TreeSetDemo.java
HashMap HashMap implements Map and extends AbstractMap. * A hash map does  not  guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are  read by an iterator. * The HashMap class is roughly equivalent to Hashtable, except  that it is unsynchronized and permits nulls. *  This implementation is not synchronized. *  HashMap lets you have null values as well as one null key Example  HashMapDemo.java
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Hash Table * Like HashMap, Hashtable stores key/value pairs  in a hash table.  When using a Hashtable, you specify an object that is used  as a key, and the value that you want linked to that key. The key  is then hashed, and the resulting hash code is used as the index at  which the value is stored within the table. * A hash table can only store objects that override the  hashCode( ) and equals( ) methods that are defined by Object.  The hashCode( ) method must compute and return the hash code  for the object. * Hashtable is synchronized * Hashtable doesn't let you have anything that's null. Example  HTDemo.java
[object Object],[object Object],[object Object],[object Object],[object Object]
PriorityQueue  *  This class is new with Java 5.  * This class implements the Queue interface. * Since the LinkedList class has been enhanced to implement the  Queue interface, basic queues can be handled with a LinkedList.  * PriorityQueue create a "priority-in, priority out" queue as opposed  to a typical FIFO queue.  *A PriorityQueue's elements are ordered either by natural ordering  (in which case the elements that are sorted first will be accessed  first) or according to a Comparator.  * In either case, the elements' ordering represents their relative priority. * Queues have a few methods not found in other collection interfaces:  peek(), poll(), and offer().
Summary
 
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Generics Generics means parameterized types. Parameterized types are important as they enable to create classes, interfaces, and methods in which the type of data upon which they  operate is specified as parameter. Using Generics its possible to create a single class that automatically works with different types of data. The class, interface or methods that operate on a parameterized type is  called generic. Example  Gen, GenDemo
Generics eliminate the process to explicitly cast to translate between  Object and type of data being operated upon. Generics work only with Objects When declaring an instance of generic type, the type argument passed to the type parameter must be a class type. Gen<int> strOb=new Gen<int>(53);  // Error cannot use primitive.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Polymorphism and Generics Polymorphism applies to the &quot;base&quot; type of the collection: List<Integer> myList = new ArrayList<Integer>(); But what about this? List<Parent> myList = new ArrayList<Child>(); List<Number> numbers = new ArrayList<Integer>(); Is this possible? No, here—the type of the variable declaration must match  the type you pass to the actual object type.  If you declare  List<Foo> foo then whatever you assign to the  foo reference MUST be of the generic type <Foo>, Not a subtype  of <Foo>,Not a supertype of <Foo>, Just <Foo>.

Más contenido relacionado

La actualidad más candente (20)

Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java util
Java utilJava util
Java util
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
07 java collection
07 java collection07 java collection
07 java collection
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Generics
GenericsGenerics
Generics
 
Standard template library
Standard template libraryStandard template library
Standard template library
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 

Destacado

Decreto2162de1983 minsalud
Decreto2162de1983 minsaludDecreto2162de1983 minsalud
Decreto2162de1983 minsaludDIEGO DAYS.
 
Cubicaje ...(1)
Cubicaje ...(1)Cubicaje ...(1)
Cubicaje ...(1)leidy95c
 
K leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de músicaK leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de músicaMagali Kleber
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
 
Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010IntegraLocal
 
Recapitulacion federalismo v1
Recapitulacion federalismo v1Recapitulacion federalismo v1
Recapitulacion federalismo v1Goyo Andión
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu isRakesh Madugula
 

Destacado (15)

Decreto2162de1983 minsalud
Decreto2162de1983 minsaludDecreto2162de1983 minsalud
Decreto2162de1983 minsalud
 
Cubicaje ...(1)
Cubicaje ...(1)Cubicaje ...(1)
Cubicaje ...(1)
 
From social data to social insight
From social data to social insightFrom social data to social insight
From social data to social insight
 
K leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de músicaK leber teorias curriculares e suas implicações no ensino superior de música
K leber teorias curriculares e suas implicações no ensino superior de música
 
Md11 gui event handling
Md11 gui event handlingMd11 gui event handling
Md11 gui event handling
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
Desigualdadesocial
DesigualdadesocialDesigualdadesocial
Desigualdadesocial
 
Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010Informa anual andalucía e inmigración 2010
Informa anual andalucía e inmigración 2010
 
Recapitulacion federalismo v1
Recapitulacion federalismo v1Recapitulacion federalismo v1
Recapitulacion federalismo v1
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu is
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 

Similar a Md08 collection api

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxeyemitra1
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.pptNaitikChatterjee
 
Collection in Java
Collection in JavaCollection in Java
Collection in JavaHome
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )charan kumar
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40bhawna sharma
 
Java collections
Java collectionsJava collections
Java collectionspadmad2291
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxsmile790243
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxrangariprajwal4554
 

Similar a Md08 collection api (20)

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java.util
Java.utilJava.util
Java.util
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
String handling
String handlingString handling
String handling
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
Array properties
Array propertiesArray properties
Array properties
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
Collection in Java
Collection in JavaCollection in Java
Collection in Java
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Java collections
Java collectionsJava collections
Java collections
 
Java collections
Java collectionsJava collections
Java collections
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 

Último

Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
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
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
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
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 

Último (20)

Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
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
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
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
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 

Md08 collection api

  • 1. Text-Based Application & Collection API
  • 2.
  • 3.
  • 4.
  • 5. Varargs With JDK 5.0 Java has included a feature that implifies the creation of methods, that need to take variable number of arguments. This feature is called varargs and it short form for variable length arguments. Prior to JDK5, variable length argument could be handled using arrays. Example PassArray With variable length arguments A variable length argument is specified by three periods(…) To write a method using varargs static void vaTest (int …v) Example VarArgs
  • 6. v is operated as an array … syntax simply tell the compiler that a variable number of arguments will be used. A method can have normal parameters along with variable length parameters, however the variable length parameter must be last parameter declared by the method. int doit(int a, int b, double c, int …vals) Overloading Vararg Methods Example VarArgs2
  • 7. String is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String . * Once a String object has been created, you cannot change the characters that comprise that string. * Each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged.
  • 8. * For those cases in which a modifiable string is desired, there is a companion class to String called StringBuffer , whose objects contain strings that can be modified after they are created. * Both the String and StringBuffer classes are declared final * The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length());
  • 9.
  • 10. // equals() vs == class EqualsNotEqualTo { public static void main(String args[]) { String s1 = &quot;Hello&quot;; String s2 = new String(s1); System.out.println(s1 + &quot; equals &quot; + s2 + &quot; &quot; + s1.equals(s2)); System.out.println(s1 + &quot; == &quot; + s2 + &quot; &quot; + (s1 == s2)); } }
  • 11.
  • 12.
  • 13.
  • 14. The core collection interfaces encapsulate different types of collections, These interfaces allow collections to be manipulated independently of the details of their representation. A Set is a special kind of Collection. A SortedSet is a special kind of Set.
  • 15. The Collection interface is the least common denominator that all collections implement * The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. Set — a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent Sets.
  • 16. List — an ordered collection (sometimes called a sequence ). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. Map — an object that maps keys to values. A Map cannot contain duplicate keys: each key can map to at most one value.
  • 17. SortedSet — a Set that maintains its elements in ascending order. Sorted sets are used for naturally ordered sets. SortedMap — a Map that maintains its mappings in ascending key order. Implementation The classes that implement these interfaces are listed below: Set HashSet TreeSet LinkedHashSet List Vector ArrayList LinkedList Map HashMap HashTable TreeMap LinkedHashMap SortedSet TreeSet SortedMap TreeMap
  • 18. Interface and class hierarchy of collections
  • 19.  
  • 20. The ArrayList Class The ArrayList class extends AbstractList and implements the List interface. * ArrayList supports dynamic arrays that can grow as needed. * An ArrayList is a variable-length array of object references. * Since this implementation use an array to store the elements of the list, so access to an element using an index is very fast. Example ArrayListDemo.java Example ArrayListToArray.java For obtaining an Array from an ArrayList.
  • 21.
  • 22.
  • 23. Vector public class Vector extends AbstractList implements List. Vector is synchronized. Vector constructors: Vector( ) The first form creates a default vector,which has an initial size of 10. Vector(int initialCapacity)   Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Vector(int initialCapacity, int capacityIncrement)            Constructs an empty vector with the specified initial capacity and capacity increment.
  • 24. Vector use an array to store the elements of the list; so access to any element using an index is very fast. Example VectorDemo.java
  • 25.
  • 26.
  • 27. The TreeSet Class * Duplicate elements are not accepted. * TreeSet provides an implementation of the SortedSet interface that uses a tree for storage. * This class guarantees that the sorted set will be in ascending element order * This implementation provides guaranteed log(n) time cost for the basic operations . * Access and retrieval times are quite fast,which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. * This implementation is not synchronized * The entries can be sorted using the Comparable interface. Example TreeSetDemo.java
  • 28. HashMap HashMap implements Map and extends AbstractMap. * A hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. * The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. * This implementation is not synchronized. * HashMap lets you have null values as well as one null key Example HashMapDemo.java
  • 29.
  • 30. Hash Table * Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. * A hash table can only store objects that override the hashCode( ) and equals( ) methods that are defined by Object. The hashCode( ) method must compute and return the hash code for the object. * Hashtable is synchronized * Hashtable doesn't let you have anything that's null. Example HTDemo.java
  • 31.
  • 32. PriorityQueue * This class is new with Java 5. * This class implements the Queue interface. * Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. * PriorityQueue create a &quot;priority-in, priority out&quot; queue as opposed to a typical FIFO queue. *A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. * In either case, the elements' ordering represents their relative priority. * Queues have a few methods not found in other collection interfaces: peek(), poll(), and offer().
  • 34.  
  • 35.
  • 36. Generics Generics means parameterized types. Parameterized types are important as they enable to create classes, interfaces, and methods in which the type of data upon which they operate is specified as parameter. Using Generics its possible to create a single class that automatically works with different types of data. The class, interface or methods that operate on a parameterized type is called generic. Example Gen, GenDemo
  • 37. Generics eliminate the process to explicitly cast to translate between Object and type of data being operated upon. Generics work only with Objects When declaring an instance of generic type, the type argument passed to the type parameter must be a class type. Gen<int> strOb=new Gen<int>(53); // Error cannot use primitive.
  • 38.
  • 39. Polymorphism and Generics Polymorphism applies to the &quot;base&quot; type of the collection: List<Integer> myList = new ArrayList<Integer>(); But what about this? List<Parent> myList = new ArrayList<Child>(); List<Number> numbers = new ArrayList<Integer>(); Is this possible? No, here—the type of the variable declaration must match the type you pass to the actual object type. If you declare List<Foo> foo then whatever you assign to the foo reference MUST be of the generic type <Foo>, Not a subtype of <Foo>,Not a supertype of <Foo>, Just <Foo>.