SlideShare a Scribd company logo
1 of 27
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 1
Topic 12
ADTS, Data Structures, Java Collections
and Generic Data Structures
"Get your data structures correct
first, and the rest of the program will
write itself."
- David Jones
Abstract Data Types
Abstract Data Types (aka ADTs) are
descriptions of how a data type will work
without implementation details
Example, Stack at NIST DADS
– http://xw2k.nist.gov/dads/HTML/stack.html
Description can be a formal, mathematical
description
Java interfaces are a form of ADTs
– some implementation details start to creep in
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 2
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
3
Data Structures
A Data Structure is:
– an implementation of an abstract data type and
– "An organization of information, usually in
computer memory", for better algorithm
efficiency."
aList
List Object
size
myElements
5
A C E B A
0 1 2 3 4 5 6 7 8 9 10
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
4
Data Structure Concepts
Data Structures are containers:
– they hold other data
– arrays are a data structure
– ... so are lists
Other types of data structures:
– stack, queue, tree,
binary search tree, hash table,
dictionary or map, set, and on and on
– www.nist.gov/dads/
– en.wikipedia.org/wiki/List_of_data_structures
Different types of data structures are optimized for
certain types of operations
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
5
Core Operations
Data Structures will have 3 core operations
– a way to add things
– a way to remove things
– a way to access things
Details of these operations depend on the
data structure
– Example: List, add at the end, access by
location, remove by location
More operations added depending on what
data structure is designed to do
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
6
ADTs and Data Structures in
Programming Languages
Modern programming languages usually
have a library of data structures
– Java collections framework
– C++ standard template library
– .Net framework (small portion of VERY large
library)
– Python lists and tuples
– Lisp lists
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
7
Data Structures in Java
Part of the Java Standard Library is the
Collections Framework
– In class we will create our own data structures
and discuss the data structures that exist in Java
A library of data structures
Built on two interfaces
– Collection
– Iterator
http://java.sun.com/j2se/1.5.0/docs/guide/coll
ections/index.html
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
8
The Java Collection interface
A generic collection
Can hold any object data type
Which type a particular collection will hold is
specified when declaring an instance of a
class that implements the Collection interface
Helps guarantee type safety at compile time
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
9
Methods in the Collection interface
public interface Collection<E>
{ public boolean add(E o)
public boolean addAll(Collection<? extends E> c)
public void clear()
public boolean contains(Object o)
public boolean containsAll(Collection<?> c)
public boolean equals(Object o)
public int hashCode()
public boolean isEmpty()
public Iterator<E> iterator()
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
public boolean retainAll(Collection<?> c)
public int size()
public Object[] toArray()
public <T> T[] toArray(T[] a)
}
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
10
The Java ArrayList Class
Implements the List interface and uses an
array as its internal storage container
It is a list, not an array
The array that actual stores the elements of
the list is hidden, not visible outside of the
ArrayList class
all actions on ArrayList objects are via the
methods
ArrayLists are generic.
– They can hold objects of any type!
CS 307 Fundamentals of
Computer Science ADTs and Data Structures
11
ArrayList's (Partial)
Class Diagram
AbstractCollection
Object
AbstractList
ArrayList
Iterable
Collection
List
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 12
Back to our Array Based List
Started with a list of ints
Don't want to have to write a new list class
for every data type we want to store in lists
Moved to an array of Objects to store the
elements of the list
// from array based list
private Object[] myCon;
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 13
Using Object
In Java, all classes inherit from exactly one
other class except Object which is at the top
of the class hierarchy
Object variables can point at objects of their
declared type and any descendants
– polymorphism
Thus, if the internal storage container is of
type Object it can hold anything
– primitives handled by wrapping them in objects.
int – Integer, char - Character
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 14
Difficulties with Object
Creating generic containers using the Object
data type and polymorphism is relatively
straight forward
Using these generic containers leads to
some difficulties
– Casting
– Type checking
Code examples on the following slides
Attendance Question 1
What is output by the following code?
ArrayList list = new ArrayList();
String name = "Olivia";
list.add(name);
System.out.print( list.get(0).charAt(2) );
A. i
B. O
C. l
D. No output due to syntax error.
E. No output due to runtime error.
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 15
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 16
Code Example - Casting
Assume a list class
ArrayList li = new ArrayList();
li.add(“Hi”);
System.out.println( li.get(0).charAt(0) );
// previous line has syntax error
// return type of get is Object
// Object does not have a charAt method
// compiler relies on declared type
System.out.println(
((String)li.get(0)).charAt(0) );
// must cast to a String
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 17
Code Example – type checking
//pre: all elements of li are Strings
public void printFirstChar(ArrayList li){
String temp;
for(int i = 0; i < li.size(); i++)
{ temp = (String)li.get(i);
if( temp.length() > 0 )
System.out.println(
temp.charAt(0) );
}
}
// what happens if pre condition not met?
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 18
Too Generic?
Does the compiler allow this?
ArrayList list = new ArrayList();
list.add( "Olivia" );
list.add( new Integer(12) );
list.add( new Rectangle() );
list.add( new ArrayList() );
A. Yes
B. No
Is this a bug or a feature?
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 19
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 20
"Fixing" the Method
//pre: all elements of li are Strings
public void printFirstChar(ArrayList li){
String temp;
for(int i = 0; i < li.size(); i++){
if( li.get(i) instanceof String ){
temp = (String)li.get(i);
if( temp.length() > 0 )
System.out.println(
temp.charAt(0) );
}
}
}
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 21
Generic Types
Java has syntax for
parameterized data types
Referred to as Generic Types in most of the
literature
A traditional parameter has a data type and
can store various values just like a variable
public void foo(int x)
Generic Types are like parameters, but the
data type for the parameter is data type
– like a variable that stores a data type
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 22
Making our Array List Generic
Data type variables declared in class header
public class GenericList<E> {
The <E> is the declaration of a data type
parameter for the class
– any legal identifier: Foo, AnyType, Element,
DataTypeThisListStores
– Sun style guide recommends terse identifiers
The value E stores will be filled in whenever
a programmer creates a new GenericList
GenericList<String> li =
new GenericList<String>();
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 23
Modifications to GenericList
instance variable
private E[] myCon;
Parameters on
– add, insert, remove, insertAll
Return type on
– get
Changes to creation of internal storage
container
myCon = (E[])new Object[DEFAULT_SIZE];
Constructor header does not change
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 24
Using Generic Types
Back to Java's ArrayList
ArrayList list1 = new ArrayList();
– still allowed, a "raw" ArrayList
– works just like our first pass at GenericList
– casting, lack of type safety
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 25
Using Generic Types
ArrayList<String> list2 =
new ArrayList<String>();
– for list2 E stores String
list2.add( "Isabelle" );
System.out.println(
list2.get(0).charAt(2) ); //ok
list2.add( new Rectangle() );
// syntax error
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 26
Parameters and Generic Types
Old version
//pre: all elements of li are Strings
public void printFirstChar(ArrayList li){
New version
//pre: none
public void printFirstChar(ArrayList<String> li){
Elsewhere
ArrayList<String> list3 = new ArrayList<String>();
printFirstChar( list3 ); // ok
ArrayList<Integer> list4 = new ArrayList<Integer>();
printFirstChar( list4 ); // syntax error
CS 307 Fundamentals of
Computer Science
ADTS and Generic Data Structures 27
Generic Types and Subclasses
ArrayList<ClosedShape> list5 =
new ArrayList<ClosedShape>();
list5.add( new Rectangle() );
list5.add( new Square() );
list5.add( new Circle() );
// all okay
list5 can store ClosedShapes and any
descendants of ClosedShape

More Related Content

Similar to Topic12ADTS_GenericDataStructures.ppt

Similar to Topic12ADTS_GenericDataStructures.ppt (20)

Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016)
 
DSA-Lecture-05
DSA-Lecture-05DSA-Lecture-05
DSA-Lecture-05
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Collection
CollectionCollection
Collection
 
C# overview part 2
C# overview part 2C# overview part 2
C# overview part 2
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Unit-I.pdf
Unit-I.pdfUnit-I.pdf
Unit-I.pdf
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.ppt
 
collections
 collections collections
collections
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
DSA 1- Introduction.pdf
DSA 1- Introduction.pdfDSA 1- Introduction.pdf
DSA 1- Introduction.pdf
 
DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Chapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.pptChapter 1 - Introduction to Data Structure.ppt
Chapter 1 - Introduction to Data Structure.ppt
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 
Data Structure Lec #1
Data Structure Lec #1Data Structure Lec #1
Data Structure Lec #1
 

Recently uploaded

VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxolyaivanovalion
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 

Recently uploaded (20)

VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 

Topic12ADTS_GenericDataStructures.ppt

  • 1. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 1 Topic 12 ADTS, Data Structures, Java Collections and Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones
  • 2. Abstract Data Types Abstract Data Types (aka ADTs) are descriptions of how a data type will work without implementation details Example, Stack at NIST DADS – http://xw2k.nist.gov/dads/HTML/stack.html Description can be a formal, mathematical description Java interfaces are a form of ADTs – some implementation details start to creep in CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 2
  • 3. CS 307 Fundamentals of Computer Science ADTs and Data Structures 3 Data Structures A Data Structure is: – an implementation of an abstract data type and – "An organization of information, usually in computer memory", for better algorithm efficiency." aList List Object size myElements 5 A C E B A 0 1 2 3 4 5 6 7 8 9 10
  • 4. CS 307 Fundamentals of Computer Science ADTs and Data Structures 4 Data Structure Concepts Data Structures are containers: – they hold other data – arrays are a data structure – ... so are lists Other types of data structures: – stack, queue, tree, binary search tree, hash table, dictionary or map, set, and on and on – www.nist.gov/dads/ – en.wikipedia.org/wiki/List_of_data_structures Different types of data structures are optimized for certain types of operations
  • 5. CS 307 Fundamentals of Computer Science ADTs and Data Structures 5 Core Operations Data Structures will have 3 core operations – a way to add things – a way to remove things – a way to access things Details of these operations depend on the data structure – Example: List, add at the end, access by location, remove by location More operations added depending on what data structure is designed to do
  • 6. CS 307 Fundamentals of Computer Science ADTs and Data Structures 6 ADTs and Data Structures in Programming Languages Modern programming languages usually have a library of data structures – Java collections framework – C++ standard template library – .Net framework (small portion of VERY large library) – Python lists and tuples – Lisp lists
  • 7. CS 307 Fundamentals of Computer Science ADTs and Data Structures 7 Data Structures in Java Part of the Java Standard Library is the Collections Framework – In class we will create our own data structures and discuss the data structures that exist in Java A library of data structures Built on two interfaces – Collection – Iterator http://java.sun.com/j2se/1.5.0/docs/guide/coll ections/index.html
  • 8. CS 307 Fundamentals of Computer Science ADTs and Data Structures 8 The Java Collection interface A generic collection Can hold any object data type Which type a particular collection will hold is specified when declaring an instance of a class that implements the Collection interface Helps guarantee type safety at compile time
  • 9. CS 307 Fundamentals of Computer Science ADTs and Data Structures 9 Methods in the Collection interface public interface Collection<E> { public boolean add(E o) public boolean addAll(Collection<? extends E> c) public void clear() public boolean contains(Object o) public boolean containsAll(Collection<?> c) public boolean equals(Object o) public int hashCode() public boolean isEmpty() public Iterator<E> iterator() public boolean remove(Object o) public boolean removeAll(Collection<?> c) public boolean retainAll(Collection<?> c) public int size() public Object[] toArray() public <T> T[] toArray(T[] a) }
  • 10. CS 307 Fundamentals of Computer Science ADTs and Data Structures 10 The Java ArrayList Class Implements the List interface and uses an array as its internal storage container It is a list, not an array The array that actual stores the elements of the list is hidden, not visible outside of the ArrayList class all actions on ArrayList objects are via the methods ArrayLists are generic. – They can hold objects of any type!
  • 11. CS 307 Fundamentals of Computer Science ADTs and Data Structures 11 ArrayList's (Partial) Class Diagram AbstractCollection Object AbstractList ArrayList Iterable Collection List
  • 12. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 12 Back to our Array Based List Started with a list of ints Don't want to have to write a new list class for every data type we want to store in lists Moved to an array of Objects to store the elements of the list // from array based list private Object[] myCon;
  • 13. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 13 Using Object In Java, all classes inherit from exactly one other class except Object which is at the top of the class hierarchy Object variables can point at objects of their declared type and any descendants – polymorphism Thus, if the internal storage container is of type Object it can hold anything – primitives handled by wrapping them in objects. int – Integer, char - Character
  • 14. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 14 Difficulties with Object Creating generic containers using the Object data type and polymorphism is relatively straight forward Using these generic containers leads to some difficulties – Casting – Type checking Code examples on the following slides
  • 15. Attendance Question 1 What is output by the following code? ArrayList list = new ArrayList(); String name = "Olivia"; list.add(name); System.out.print( list.get(0).charAt(2) ); A. i B. O C. l D. No output due to syntax error. E. No output due to runtime error. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 15
  • 16. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 16 Code Example - Casting Assume a list class ArrayList li = new ArrayList(); li.add(“Hi”); System.out.println( li.get(0).charAt(0) ); // previous line has syntax error // return type of get is Object // Object does not have a charAt method // compiler relies on declared type System.out.println( ((String)li.get(0)).charAt(0) ); // must cast to a String
  • 17. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 17 Code Example – type checking //pre: all elements of li are Strings public void printFirstChar(ArrayList li){ String temp; for(int i = 0; i < li.size(); i++) { temp = (String)li.get(i); if( temp.length() > 0 ) System.out.println( temp.charAt(0) ); } } // what happens if pre condition not met?
  • 18. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 18 Too Generic? Does the compiler allow this? ArrayList list = new ArrayList(); list.add( "Olivia" ); list.add( new Integer(12) ); list.add( new Rectangle() ); list.add( new ArrayList() ); A. Yes B. No
  • 19. Is this a bug or a feature? CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 19
  • 20. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 20 "Fixing" the Method //pre: all elements of li are Strings public void printFirstChar(ArrayList li){ String temp; for(int i = 0; i < li.size(); i++){ if( li.get(i) instanceof String ){ temp = (String)li.get(i); if( temp.length() > 0 ) System.out.println( temp.charAt(0) ); } } }
  • 21. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 21 Generic Types Java has syntax for parameterized data types Referred to as Generic Types in most of the literature A traditional parameter has a data type and can store various values just like a variable public void foo(int x) Generic Types are like parameters, but the data type for the parameter is data type – like a variable that stores a data type
  • 22. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 22 Making our Array List Generic Data type variables declared in class header public class GenericList<E> { The <E> is the declaration of a data type parameter for the class – any legal identifier: Foo, AnyType, Element, DataTypeThisListStores – Sun style guide recommends terse identifiers The value E stores will be filled in whenever a programmer creates a new GenericList GenericList<String> li = new GenericList<String>();
  • 23. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 23 Modifications to GenericList instance variable private E[] myCon; Parameters on – add, insert, remove, insertAll Return type on – get Changes to creation of internal storage container myCon = (E[])new Object[DEFAULT_SIZE]; Constructor header does not change
  • 24. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 24 Using Generic Types Back to Java's ArrayList ArrayList list1 = new ArrayList(); – still allowed, a "raw" ArrayList – works just like our first pass at GenericList – casting, lack of type safety
  • 25. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 25 Using Generic Types ArrayList<String> list2 = new ArrayList<String>(); – for list2 E stores String list2.add( "Isabelle" ); System.out.println( list2.get(0).charAt(2) ); //ok list2.add( new Rectangle() ); // syntax error
  • 26. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 26 Parameters and Generic Types Old version //pre: all elements of li are Strings public void printFirstChar(ArrayList li){ New version //pre: none public void printFirstChar(ArrayList<String> li){ Elsewhere ArrayList<String> list3 = new ArrayList<String>(); printFirstChar( list3 ); // ok ArrayList<Integer> list4 = new ArrayList<Integer>(); printFirstChar( list4 ); // syntax error
  • 27. CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 27 Generic Types and Subclasses ArrayList<ClosedShape> list5 = new ArrayList<ClosedShape>(); list5.add( new Rectangle() ); list5.add( new Square() ); list5.add( new Circle() ); // all okay list5 can store ClosedShapes and any descendants of ClosedShape