SlideShare a Scribd company logo
DATA STRUCTURES IN JAVA
Arun Seetharaman
March 10, 1998
TOPIC OBJECTIVES
• Understand some useful data structures in the java.util
package
• The Observer-Observable pattern
• Java Collection Framework
• Iterators
DATA STRUCTURES
• Well designed java.util package
• A bunch of dynamic data structures
• You do not have to write linked lists and hash tables
• Could be building blocks for more complicated data
structures
THE “VECTOR” CLASS
• A very generic structure for storing and retrieving
objects
• A very simple structure to use
• Tries to optimize storage, resulting in some extra
capacity at times
• Removal of elements closes the holes created
VECTOR OPERATIONS
public void addElement(Object);
public void clear();
public Object elementAt(int);
public void insertElementAt(
Object, int);
public void removeElementAt(int);
public void setElementAt(
Object, int);
public int size();
THE “HASHTABLE” CLASS
• Useful for searchable data structures
• Stores key-value pairs
• Key-based search mechanism
• Better than Vector for large amount of data that need
to be searched
public Object get(Object);
public Object put(Object,Object);
protected void rehash();
CALENDARS
• Date: mostly deprecated as of JDK1.1
• Calendar: Convert Date objects to fields
• GregorianCalendar: Important class that cater to the
differences between Julian date and Gregorian date.
Also understands timezones
• TimeZone: represents any timezone with the GMT offset
THE BITSET CLASS
• Represents a collection of bits
• Grows dynamically as bits are required
• Bits accessed using 0-based index
• public void and(BitSet);
• public void andNot(BitSet);
• public void or(BitSet);
• public void xor(BitSet);
OBSERVER-OBSERVABLE
PATTERN
• Update multiple objects from a common source of
data
• Displaying data in multiple formats like charts,
worksheet is a common example
• More often implemented using the MVC design pattern
THE “OBSERVABLE”
CLASS
• Represents the data source
• Can have one or more observers
void addObserver(Observer);
void deletebserver(Observer);
void notifyObservers(Object);
void setChanged();
boolean hasChanged();
void clearChanged();
AN OBSERVABLE ENTITY
class MsgObservable extends Observable
implements Runnable {
public void run() {
while(true) {
msg = waitForMsg();
setChanged();
notifyObservers(msg);
}
}
}
THE “OBSERVER”
INTERFACE
• Implemented when changes in an “Observable”
object need to be informed
• update is invoked, when the Observable object calls
the notifyObservers method
class LogServer implements Observer {
public void update(Observable obs,
Object obj) {
logTheMsg(obj);
}
}
WHAT IS A COLLECTION
FRAMEWORK?
• Unified Architecture
• Interfaces : implementation-independence
• Implementations : reusable data structures
• Algorithms : reusable functionality
• Best-known examples
• C++ Standard Template Library (STL)
• Smalltalk
ARCHITECTURE
OVERVIEW
• Core Collection Interfaces
• General-Purpose Implementations
• Wrapper Implementations
• Abstract Implementations
• Algorithms
CORE COLLECTION
INTERFACES
COLLECTION INTERFACE
public interface Collection {
int size();
boolean isEmpty();
boolean contains(Object element);
Iterator iterator();
Object[] toArray();
Object[] toArray(Object a[]);
}
ITERATOR INTERFACE
• Replacement for Enumeration interface
• Adds remove method
• Improves method names
public interface Iterator {
boolean hasNext();
Object next();
void remove(); // Optional
}
COLLECTION EXAMPLE
public static boolean removeNulls(
Collection c) {
boolean modified = false;
for (Iterator i=c.iterator();i.hasNext();){
if (i.next()==null) {
i.remove();
modified = true;
}
}
return modified;
}
SET INTERFACE
• Adds no methods to Collection!
• Adds stipulation: no duplicate elements
• Mandates equals and hashCode calculation
public interface Set
extends Collection {
}
SET IDIOMS
Set s1, s2;
boolean subset = s1.containsAll(s2);
Set union = new HashSet(s1).addAll(s2);
Set intersection = new
HashSet(s1).retainAll(s2);
Set difference = new
HashSet(s1).removeAll(s2);
LIST INTERFACE
• A sequence of objects
public interface List
extends Collection {
Object get(int);
int lastIndexOf(Object);
int lastIndexOf(Object, int);
ListIterator listIterator(int);
…
}
LIST EXAMPLE
• Reusable algorithms to swap elements and randomize
public static void swap(List a,
int i, int j) {
Object tmp = a.get(i);
a.set(i, a.get(j));
a.set(j, tmp);
}
public static void randomize(List a) {
for (int i=a.size(); i>1; i--)
swap(a, i-1,
(r.nextInt() &~ (1<<31)) % i);
}
MAP INTERFACE
• A key-value mapping
public interface Map {
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
Object get(Object key);
public Set keySet();
public Collection values();
public Set entries();
}
MAP IDIOMS
Map m;
for (iterator i=m.keySet().iterator();
i.hasNext(); )
System.out.println(i.next());
Map a, b;
boolean isSubMap =
a.entries().containsAll(b.entries());
Set commonKeys = new
HashSet(a.keySet()).retainAll(b.keySet);
GENERAL-PURPOSE
IMPLEMENTATIONS
COLLECTIONS
• Exclusively static methods
• Contains polymorphic algorithms
• Work on collections
• Implementers can substitute algorithms
SYNCHRONIZATION
WRAPPERS
• Anonymous implementations, one per core interface
• Static factories take collection of appropriate type
• Thread-safety assured if all access via wrapper
• Iteration must be synchronized manually
SYNCHRONIZATION
WRAPPER EXAMPLE
Set s = Collections.synchronizedSet(
newHashSet());
...s.add("wombat");
// Thread-safe ...
synchronized(s) {
Iterator i = s.iterator(); // In synch block!
while (i.hasNext())
System.out.println(i.next());
}
UNMODIFIABLE
WRAPPERS
• Unmodifiable wrappers
• Analogous to synchronization wrappers
• Provide read-only access
• Available for core interfaces
CONVENIENCE
WRAPPERS
• List-view of arrays
• Multiple-copy list
• Singletons
• Empty collections
SOME NEEDS FOR
CUSTOMIZATION
• Persistence
• Highly concurrent collections
• High-performance, special-purpose
• Space-efficient representations
• Fancy data structures
• Convenience classes
REUSABLE ALGORITHMS
• Sorting
• Searching
• Shuffling
• Data Manipulation
• Extreme Values
ALGORITHMS: SORTING
• Uses an optimized merge sort
• Doesn’t reorder equal elements
• static void sort(List);
• static void sort(List, Comparator);
COMPARABLE AND
COMPARATOR
• Comparable: uses the natural ordering for that object
type
• int compareTo(Object);
• Comparator: can define custom ordering for object
• int compare(Object, Object);
• boolean equals(Object);
ALGORITHMS:
SEARCHING
• Works on sorted lists
• Uses the binary search algorithm
• int binarySearch(List, Object);
• int binarySearch(List, Object, Comparator);
ALGORITHMS: SHUFFLING
• Force randomness in the Collection
• A random object defines the randomness for the shuffle
operation
• void shuffle(List);
• void shuffle(List, Random);
OTHER ALGORITHMS
• Data Manipulation:
• void copy(List, List);
• void fill(List, Object);
• void reverse(List);
• Extreme Values:
• Object max/min(Collection);
• Object max/min(Collection, Comparator);
COMPATIBILITY
• Upward Compatibility
• Vector implements List
• Hashtable implements Map
• Arrays.toList(myArray)
• Backward Compatibility
• myCollection.toArray()
• Vector(myCollection)
• Hashtable(myMap)
TOPIC SUMMARY
• The java.util package has a good collection of data
structures
• Classes to support the Observer-Observable pattern
• Collection framework for improved data structures
• Many reusable algorithms implemented
Ad

More Related Content

Similar to Data Structures in Java and Introduction to Collection Framework (20)

Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Davorin Vukelic
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
Ismail Mayat
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
Arpit Poladia
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
Dr. SURBHI SAROHA
 
Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
Collections
CollectionsCollections
Collections
Marwa Dosoky
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Java util
Java utilJava util
Java util
Srikrishna k
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
Chris Adamson
 
The Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API designThe Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API design
Miro Cupak
 
JCache Using JCache
JCache Using JCacheJCache Using JCache
JCache Using JCache
日本Javaユーザーグループ
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
Prem Kumar Badri
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払いクリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
Shinya Mochida
 
Persistences
PersistencesPersistences
Persistences
Training Guide
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Davorin Vukelic
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
Ismail Mayat
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
Arpit Poladia
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
Chris Adamson
 
The Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API designThe Good, the Bad and the Ugly of Java API design
The Good, the Bad and the Ugly of Java API design
Miro Cupak
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
Prem Kumar Badri
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払いクリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
Shinya Mochida
 

More from Arun Seetharaman (14)

Implementing Load Balancing in COM+ Applications
Implementing Load Balancing in COM+ ApplicationsImplementing Load Balancing in COM+ Applications
Implementing Load Balancing in COM+ Applications
Arun Seetharaman
 
Advanced Windows DNA Scripting with Visual InterDev
Advanced Windows DNA Scripting with Visual InterDevAdvanced Windows DNA Scripting with Visual InterDev
Advanced Windows DNA Scripting with Visual InterDev
Arun Seetharaman
 
Implementing DHTML Behavior Script Components
Implementing DHTML Behavior Script ComponentsImplementing DHTML Behavior Script Components
Implementing DHTML Behavior Script Components
Arun Seetharaman
 
Creating Data-based Applications Using DHTML
Creating Data-based Applications Using DHTMLCreating Data-based Applications Using DHTML
Creating Data-based Applications Using DHTML
Arun Seetharaman
 
COM Events for Late-bound Delivery of Information
COM Events for Late-bound Delivery of InformationCOM Events for Late-bound Delivery of Information
COM Events for Late-bound Delivery of Information
Arun Seetharaman
 
Understanding Windows NT Internals - Part 4
Understanding Windows NT Internals - Part 4Understanding Windows NT Internals - Part 4
Understanding Windows NT Internals - Part 4
Arun Seetharaman
 
Understanding Windows NT Internals - Part 5
Understanding Windows NT Internals - Part 5Understanding Windows NT Internals - Part 5
Understanding Windows NT Internals - Part 5
Arun Seetharaman
 
Understanding Windows NT Internals - Part 3
Understanding Windows NT Internals - Part 3Understanding Windows NT Internals - Part 3
Understanding Windows NT Internals - Part 3
Arun Seetharaman
 
Understanding Windows NT Internals - Part 1
Understanding Windows NT Internals - Part 1Understanding Windows NT Internals - Part 1
Understanding Windows NT Internals - Part 1
Arun Seetharaman
 
Understanding Windows NT Internals - Part 2
Understanding Windows NT Internals - Part 2Understanding Windows NT Internals - Part 2
Understanding Windows NT Internals - Part 2
Arun Seetharaman
 
OLE DB Provider Development - Encapsulating a Service Provider
OLE DB Provider Development - Encapsulating a Service ProviderOLE DB Provider Development - Encapsulating a Service Provider
OLE DB Provider Development - Encapsulating a Service Provider
Arun Seetharaman
 
OLE DB 2.0 Architecture - Supporting Remote Data Exchange
OLE DB 2.0 Architecture - Supporting Remote Data ExchangeOLE DB 2.0 Architecture - Supporting Remote Data Exchange
OLE DB 2.0 Architecture - Supporting Remote Data Exchange
Arun Seetharaman
 
AWT Enhancements in V1.1 - Supporting Richer GUI Development
AWT Enhancements in V1.1 - Supporting Richer GUI DevelopmentAWT Enhancements in V1.1 - Supporting Richer GUI Development
AWT Enhancements in V1.1 - Supporting Richer GUI Development
Arun Seetharaman
 
Java Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIsJava Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIs
Arun Seetharaman
 
Implementing Load Balancing in COM+ Applications
Implementing Load Balancing in COM+ ApplicationsImplementing Load Balancing in COM+ Applications
Implementing Load Balancing in COM+ Applications
Arun Seetharaman
 
Advanced Windows DNA Scripting with Visual InterDev
Advanced Windows DNA Scripting with Visual InterDevAdvanced Windows DNA Scripting with Visual InterDev
Advanced Windows DNA Scripting with Visual InterDev
Arun Seetharaman
 
Implementing DHTML Behavior Script Components
Implementing DHTML Behavior Script ComponentsImplementing DHTML Behavior Script Components
Implementing DHTML Behavior Script Components
Arun Seetharaman
 
Creating Data-based Applications Using DHTML
Creating Data-based Applications Using DHTMLCreating Data-based Applications Using DHTML
Creating Data-based Applications Using DHTML
Arun Seetharaman
 
COM Events for Late-bound Delivery of Information
COM Events for Late-bound Delivery of InformationCOM Events for Late-bound Delivery of Information
COM Events for Late-bound Delivery of Information
Arun Seetharaman
 
Understanding Windows NT Internals - Part 4
Understanding Windows NT Internals - Part 4Understanding Windows NT Internals - Part 4
Understanding Windows NT Internals - Part 4
Arun Seetharaman
 
Understanding Windows NT Internals - Part 5
Understanding Windows NT Internals - Part 5Understanding Windows NT Internals - Part 5
Understanding Windows NT Internals - Part 5
Arun Seetharaman
 
Understanding Windows NT Internals - Part 3
Understanding Windows NT Internals - Part 3Understanding Windows NT Internals - Part 3
Understanding Windows NT Internals - Part 3
Arun Seetharaman
 
Understanding Windows NT Internals - Part 1
Understanding Windows NT Internals - Part 1Understanding Windows NT Internals - Part 1
Understanding Windows NT Internals - Part 1
Arun Seetharaman
 
Understanding Windows NT Internals - Part 2
Understanding Windows NT Internals - Part 2Understanding Windows NT Internals - Part 2
Understanding Windows NT Internals - Part 2
Arun Seetharaman
 
OLE DB Provider Development - Encapsulating a Service Provider
OLE DB Provider Development - Encapsulating a Service ProviderOLE DB Provider Development - Encapsulating a Service Provider
OLE DB Provider Development - Encapsulating a Service Provider
Arun Seetharaman
 
OLE DB 2.0 Architecture - Supporting Remote Data Exchange
OLE DB 2.0 Architecture - Supporting Remote Data ExchangeOLE DB 2.0 Architecture - Supporting Remote Data Exchange
OLE DB 2.0 Architecture - Supporting Remote Data Exchange
Arun Seetharaman
 
AWT Enhancements in V1.1 - Supporting Richer GUI Development
AWT Enhancements in V1.1 - Supporting Richer GUI DevelopmentAWT Enhancements in V1.1 - Supporting Richer GUI Development
AWT Enhancements in V1.1 - Supporting Richer GUI Development
Arun Seetharaman
 
Java Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIsJava Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIs
Arun Seetharaman
 
Ad

Recently uploaded (20)

GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Ad

Data Structures in Java and Introduction to Collection Framework

  • 1. DATA STRUCTURES IN JAVA Arun Seetharaman March 10, 1998
  • 2. TOPIC OBJECTIVES • Understand some useful data structures in the java.util package • The Observer-Observable pattern • Java Collection Framework • Iterators
  • 3. DATA STRUCTURES • Well designed java.util package • A bunch of dynamic data structures • You do not have to write linked lists and hash tables • Could be building blocks for more complicated data structures
  • 4. THE “VECTOR” CLASS • A very generic structure for storing and retrieving objects • A very simple structure to use • Tries to optimize storage, resulting in some extra capacity at times • Removal of elements closes the holes created
  • 5. VECTOR OPERATIONS public void addElement(Object); public void clear(); public Object elementAt(int); public void insertElementAt( Object, int); public void removeElementAt(int); public void setElementAt( Object, int); public int size();
  • 6. THE “HASHTABLE” CLASS • Useful for searchable data structures • Stores key-value pairs • Key-based search mechanism • Better than Vector for large amount of data that need to be searched public Object get(Object); public Object put(Object,Object); protected void rehash();
  • 7. CALENDARS • Date: mostly deprecated as of JDK1.1 • Calendar: Convert Date objects to fields • GregorianCalendar: Important class that cater to the differences between Julian date and Gregorian date. Also understands timezones • TimeZone: represents any timezone with the GMT offset
  • 8. THE BITSET CLASS • Represents a collection of bits • Grows dynamically as bits are required • Bits accessed using 0-based index • public void and(BitSet); • public void andNot(BitSet); • public void or(BitSet); • public void xor(BitSet);
  • 9. OBSERVER-OBSERVABLE PATTERN • Update multiple objects from a common source of data • Displaying data in multiple formats like charts, worksheet is a common example • More often implemented using the MVC design pattern
  • 10. THE “OBSERVABLE” CLASS • Represents the data source • Can have one or more observers void addObserver(Observer); void deletebserver(Observer); void notifyObservers(Object); void setChanged(); boolean hasChanged(); void clearChanged();
  • 11. AN OBSERVABLE ENTITY class MsgObservable extends Observable implements Runnable { public void run() { while(true) { msg = waitForMsg(); setChanged(); notifyObservers(msg); } } }
  • 12. THE “OBSERVER” INTERFACE • Implemented when changes in an “Observable” object need to be informed • update is invoked, when the Observable object calls the notifyObservers method class LogServer implements Observer { public void update(Observable obs, Object obj) { logTheMsg(obj); } }
  • 13. WHAT IS A COLLECTION FRAMEWORK? • Unified Architecture • Interfaces : implementation-independence • Implementations : reusable data structures • Algorithms : reusable functionality • Best-known examples • C++ Standard Template Library (STL) • Smalltalk
  • 14. ARCHITECTURE OVERVIEW • Core Collection Interfaces • General-Purpose Implementations • Wrapper Implementations • Abstract Implementations • Algorithms
  • 16. COLLECTION INTERFACE public interface Collection { int size(); boolean isEmpty(); boolean contains(Object element); Iterator iterator(); Object[] toArray(); Object[] toArray(Object a[]); }
  • 17. ITERATOR INTERFACE • Replacement for Enumeration interface • Adds remove method • Improves method names public interface Iterator { boolean hasNext(); Object next(); void remove(); // Optional }
  • 18. COLLECTION EXAMPLE public static boolean removeNulls( Collection c) { boolean modified = false; for (Iterator i=c.iterator();i.hasNext();){ if (i.next()==null) { i.remove(); modified = true; } } return modified; }
  • 19. SET INTERFACE • Adds no methods to Collection! • Adds stipulation: no duplicate elements • Mandates equals and hashCode calculation public interface Set extends Collection { }
  • 20. SET IDIOMS Set s1, s2; boolean subset = s1.containsAll(s2); Set union = new HashSet(s1).addAll(s2); Set intersection = new HashSet(s1).retainAll(s2); Set difference = new HashSet(s1).removeAll(s2);
  • 21. LIST INTERFACE • A sequence of objects public interface List extends Collection { Object get(int); int lastIndexOf(Object); int lastIndexOf(Object, int); ListIterator listIterator(int); … }
  • 22. LIST EXAMPLE • Reusable algorithms to swap elements and randomize public static void swap(List a, int i, int j) { Object tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } public static void randomize(List a) { for (int i=a.size(); i>1; i--) swap(a, i-1, (r.nextInt() &~ (1<<31)) % i); }
  • 23. MAP INTERFACE • A key-value mapping public interface Map { int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); Object get(Object key); public Set keySet(); public Collection values(); public Set entries(); }
  • 24. MAP IDIOMS Map m; for (iterator i=m.keySet().iterator(); i.hasNext(); ) System.out.println(i.next()); Map a, b; boolean isSubMap = a.entries().containsAll(b.entries()); Set commonKeys = new HashSet(a.keySet()).retainAll(b.keySet);
  • 26. COLLECTIONS • Exclusively static methods • Contains polymorphic algorithms • Work on collections • Implementers can substitute algorithms
  • 27. SYNCHRONIZATION WRAPPERS • Anonymous implementations, one per core interface • Static factories take collection of appropriate type • Thread-safety assured if all access via wrapper • Iteration must be synchronized manually
  • 28. SYNCHRONIZATION WRAPPER EXAMPLE Set s = Collections.synchronizedSet( newHashSet()); ...s.add("wombat"); // Thread-safe ... synchronized(s) { Iterator i = s.iterator(); // In synch block! while (i.hasNext()) System.out.println(i.next()); }
  • 29. UNMODIFIABLE WRAPPERS • Unmodifiable wrappers • Analogous to synchronization wrappers • Provide read-only access • Available for core interfaces
  • 30. CONVENIENCE WRAPPERS • List-view of arrays • Multiple-copy list • Singletons • Empty collections
  • 31. SOME NEEDS FOR CUSTOMIZATION • Persistence • Highly concurrent collections • High-performance, special-purpose • Space-efficient representations • Fancy data structures • Convenience classes
  • 32. REUSABLE ALGORITHMS • Sorting • Searching • Shuffling • Data Manipulation • Extreme Values
  • 33. ALGORITHMS: SORTING • Uses an optimized merge sort • Doesn’t reorder equal elements • static void sort(List); • static void sort(List, Comparator);
  • 34. COMPARABLE AND COMPARATOR • Comparable: uses the natural ordering for that object type • int compareTo(Object); • Comparator: can define custom ordering for object • int compare(Object, Object); • boolean equals(Object);
  • 35. ALGORITHMS: SEARCHING • Works on sorted lists • Uses the binary search algorithm • int binarySearch(List, Object); • int binarySearch(List, Object, Comparator);
  • 36. ALGORITHMS: SHUFFLING • Force randomness in the Collection • A random object defines the randomness for the shuffle operation • void shuffle(List); • void shuffle(List, Random);
  • 37. OTHER ALGORITHMS • Data Manipulation: • void copy(List, List); • void fill(List, Object); • void reverse(List); • Extreme Values: • Object max/min(Collection); • Object max/min(Collection, Comparator);
  • 38. COMPATIBILITY • Upward Compatibility • Vector implements List • Hashtable implements Map • Arrays.toList(myArray) • Backward Compatibility • myCollection.toArray() • Vector(myCollection) • Hashtable(myMap)
  • 39. TOPIC SUMMARY • The java.util package has a good collection of data structures • Classes to support the Observer-Observable pattern • Collection framework for improved data structures • Many reusable algorithms implemented