SlideShare a Scribd company logo
Java 103: Intro to Java Data
Structures
Introduction
• Your Name: Manuela Grindei
• Your day job: Software Developer @ Gamesys
• Your last holiday destination: Vienna
Java 103
• Data Structures
– Arrays
– Java Collections Framework
– Collection Algorithms
Java 103: Intro to Java Data
Structures
Arrays
Arrays
• Indexed sequence of values of the same type
• Store and manipulate huge quantities of data
• Examples:
– 52 playing cards in a deck
– Thousand undergrads at Hult
– 1 million characters in a book
– 10 million audio samples in an MP3 file
– 4 billion nucleotides in a DNA strand
– 73 billion Google queries per year
– 50 trillion cells in the human body
– 6.02 x 10e23 particles in a mole
Many Variables of the Same Type
• Example: Goal is to store 10 variables of the same
type without Arrays
Many Variables of the Same Type
• Example: Goal is to store 10 variables of the same
type Arrays
Arrays in Java
• Java has special language support for arrays
– To make an array: declare, create, and initialize it
– To access element i of array named a, use a[i]
– Array indices start at 0 and end at a.length - 1
• Compact alternative
– Declare, create, and initialize in one statement
– Default initialization: all numbers automatically set to zero
Array Processing Examples
Two-Dimensional Arrays
• Examples
– Table of data for each experiment and outcome
– Table of grades for each student and assignments
– Table of gray scale values for each pixel in a 2D image
• Mathematical abstraction
– Matrix
• Java abstraction
– 2D array
Two-Dimensional Arrays in Java
• Array Access
– Use a[i][j] to access element in row i and column j
– Zero-based indexing
– Row and column indices start at 0
Setting Array Values at Compile Time
• Initialize 2D array by listing values
Arrays Summary
• Organized way to store huge quantities of data
• Almost as easy to use as primitive types
• Can directly access an element given its index
Hands-on Exercise
Array of Days
Exercise: Array of Days
• Create a new Java project in Eclipse named ArrayOfDays
• Create a java class named DayPrinter that prints out
names of the days in a week from an array.
Solution : Arrays of Days
public class DayPrinter {
public static void main(String[] args) {
//initialise the array with the names of days of the
week
String[] daysOfTheWeek =
{"Sunday","Monday","Tuesday","Wednesday",
"Thuesday","Friday”,"Saturday"};
//loop through the array and print their elements to
//stdout
for (int i= 0;i < daysOfTheWeek.length;i++ ){
System.out.println(daysOfTheWeek[i]);
}
}
}
% javac DayPrinter.java
% java DayPrinter
Sunday
Monday
Tuesday
Wednesday
Thuesday
Friday
Saturday
Java 103: Intro to Java Data
Structures
Java Collections Framework
What is a Collection?
• An object that groups multiple items into a single
unit
• Used to store, retrieve, manipulate, and
communicate aggregate data
• Represent data items that form a natural group,
– a poker hand (a collection of cards)
– a mail folder (a collection of letters)
– a telephone directory (a mapping of names to phone
numbers)
Collections Framework
• A unified architecture for representing and
manipulating collections
• Usually contain…
– Interfaces
– Implementations
– Algorithms
• Examples of collections frameworks in other
languages
– C++ Standard Template Library (STL)
– Smalltalk's collection hierarchy
Java Collections Framework
• Interfaces
Collection
List Set
Iterable
SortedSet Dequeue
Queue
NavigableSet NavigableMap
SortedMap
Map
Note: Map does not
extend Collection;
but it is a “collection”
Collection Interface
• Contains about a dozen methods that describe
common operations on groups of objects
• Commonly Used Methods
– add(Object x) adds x to the collection
– remove(Object x) removes x from the collection
– contains(Object x) returns true if x is in collection
– size () return number of elements
– toArray() returns an array containing elements
– iterator() returns an Iterator object for accessing the
elements
Hands-on Exercise
Dumping Collection Elements
Exercise: Dumping Collection Elements
• What happens when you run the following program?
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class DumpCollection {
public static void main(String[] args) {
Collection days= Arrays.asList(”Mon",”Tues",”Wed",”Thurs",”Fri",”Sat", ”Sun");
dumpCollection(days);
}
public static void dumpCollection(Collection c){
System.out.println("collection has " + c.size() + " elements");
Iterator iterator = c.iterator();
while (iterator.hasNext()){
System.out.println("Next element is " + iterator.next());
}
}
}
List Interface
• Keeps its elements in the order in which they are
added
• Each element has an index starting from 0
(similar to an array)
• Commonly Used Methods
– add (int index, Object x) insert x at index
– get (int index) returns the element at index
– indexOf(Object x) returns the index of the first
occurrance of x
– remove (int index) removes the element at index
List World
List
ArrayList
LinkedList
List World
List
ArrayList
LinkedList
Fast iteration and fast
random access
List World
List
ArrayList
LinkedList
Fast iteration and fast
random access
Good for adding
elements to the ends,
i.e. stacks and queues
Hands-on Exercise
Creating a TODO List
Exercise: Simple TODO List
• Create a Java project in Eclipse named
SimpleTodoList
• Create a Java program named SimpleTodoList
• Create a List to store your todo list items (use
either ArrayList or LinkedList)
• Use a for-loop to display your list contents
Solution: Simple TODO List
import java.util.ArrayList;
public class SimpleTodoList {
public static void main(String[] args) {
ArrayList<String> todoList = new ArrayList<String>();
todoList.add("make breakfast");
todoList.add("read morning paper");
todoList.add("Doctors appointment");
for (String item : todoList ) {
System.out.println("Item:" + item) ;
}
}
}
Set Interface
• Sets contain an unordered list of elements
• They do not allow duplicate elements
• Commonly Used Methods
– add (Object x) returns true if x doesn’t already
exist and false if it exists
Set World
Set
HashSet
LinkedHashSet
TreeSet
Set World
Set
HashSet
LinkedHashSet
TreeSet
Fast access, assures no
duplicates, provides no
ordering
Set World
Set
HashSet
LinkedHashSet
TreeSet
Fast access, assures no
duplicates, provides no
ordering
No duplicates; iterates
by insertion order
No duplicates; iterates
by insertion order
Set World
Set
HashSet
LinkedHashSet
TreeSet
Fast access, assures no
duplicates, provides no
ordering
No duplicates; iterates
by insertion order
No duplicates;
iterates in
sorted order
Hands-on Exercise
Set of Points
Example: Set of Points
• What happens when you run the following program?
import java.awt.Point;
import java.util.HashSet;
import java.util.Set;
public class AddTwice {
public static void main(String[] args) {
Set points = new HashSet();
Point p1 = new Point(10,20);
Point p2 = new Point(10,20);
points.add(p1);
points.add(p2);
System.out.println("number of points = " + points.size());
}
}
Map Interface
• Combines two collections called keys and values
• Associates exactly one value with each key
• Keys are used to get values from Maps
• Commonly Used Methods
– put (Object key, Object value) associates a key and a value
– get(Object key) returns the value associated with key
– containsKey (Object key) return true if the Map associates
some value with key
– keySet() returns a Set containing the Map’s keys
– values() returns a Collection containing the Map’s values
Map World
Map
LinkedHashMap
TreeMap
HashMap
Map World
Map
LinkedHashMap
TreeMap
HashMap
Fastest updates (key/values);
allows one null key, many
null values
Map World
Map
LinkedHashMap
TreeMap
Faster iterations; iterates
by insertion order or last
accessed; allows one null
key, many null values
HashMap
Fastest updates (key/values);
allows one null key, many
null values
Map World
Map
LinkedHashMap
TreeMap
Faster iterations; iterates
by insertion order or last
accessed; allows one null
key, many null values
A sorted map
HashMap
Fastest updates (key/values);
allows one null key, many
null values
Hands-on Exercise
Word Frequency Table
Example: Word Frequency Table
import java.util.*;
/**
* Creates a word frequency table from command line arguments
*/
public class WordFrequency {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
} % java WordFrequency if it is to be it is up to me to delegate
8 distinct words:
{to=3, is=2, it=2, if=1, me=1, delegate=1, up=1, be=1}
Collection Framework Summary
• Reduces programming effort
• Increases program speed and quality
• Allows interoperability among unrelated APIs
• Reduces effort to learn and to use new APIs
• Reduces effort to design new APIs
• Fosters software reuse
Key Methods in List, Set, and Map
Key Interface Methods List Set Map Descriptions
boolean add(element)
boolean add(index, element)
X
X
X Add an element. For Lists, optionally
add the element at an index point
boolean contains(object)
boolean containsKey(object key)
boolean containsValue(object value)
X X
X
X
Search a collection for an object (or,
optionally for Maps a key), return the
result as a boolean
object get(index)
object get(key)
X
X
Get an object from a collection, via an
index or a key
int indexOf(object) X Get the location of an object in a List
Iterator iterator() X X Get an Iterator for a List or a Set
Set keySet() X Return a Set containing a Map’s keys
put(key, value) X Add a key/value pair to a Map
remove(index)
remove(object)
remove(key)
X
X X
X
Remove an element via an index, or
via the element’s value, or via a key
int size() X X X Return the number of elements in a
collection
Object[] toArray() X X Return an array containing the
Java 103: Intro to Java
Collections
Collection Algorithms
Collection Algorithms
• Arrays Class
– Contains static methods for operations on Arrays
– Commonly Used Methods
• asList(Array array)
• sort (Array array)
• Collections Class
– Contains static methods for operations on Collections
– Commonly Used Methods
• sort (List list)
• binarySearch(List list, Object key)
Hands-on Exercise
Sorting Arrays and Collections
Example: Sorting Arrays
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArraySort {
public static void main(String[] args) {
String[] months = {"Jan","Feb","Mar","Apr","May","June", "July", "Aug",
"Sept","Oct","Nov","Dec"};
Arrays.sort(months);
for (Object month :months){
System.out.println(month);
}
}
}
% java ArraySort
Aug
Dec
Feb
Jan
July
June
Mar
May
Nov
Oct
Sept
Example: Sorting Collections
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionSort {
public static void main(String[] args) {
List months = Arrays.asList("Jan","Feb","Mar","Apr","May","June", "July", "Aug",
"Sept","Oct","Nov","Dec");
Collections.sort(months);
for (Object month :months){
System.out.println(month);
}
}
}
% java CollectionSort
Aug
Dec
Feb
Jan
July
June
Mar
May
Nov
Oct
Sept
Collection Algorithms Summary
• Collection algorithms enable sorting and
searching of collections
• Most algorithms are in …
– java.util.Collections
– java.utils.Arrays
Resources
• Collections Framework Tutorial: http://docs.oracle.com/javase/tutorial/collections/
• Official Java Collections Framework Documentation:
http://docs.oracle.com/javase/8/docs/technotes/guides/collections/

More Related Content

What's hot

Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
Naveen Sagayaselvaraj
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manualLaura Popovici
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
manikanta361
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
Manuela Grindei
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 

What's hot (20)

Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 

Similar to Java 103

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
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Data Structure Lec #1
Data Structure Lec #1Data Structure Lec #1
Data Structure Lec #1
University of Gujrat, Pakistan
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.ppt
omair31
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
ShahinAhmed49
 
Data structure and algorithm with java by shikra
Data structure and algorithm  with java by shikraData structure and algorithm  with java by shikra
Data structure and algorithm with java by shikra
jateno3396
 
Java Collections
Java  Collections Java  Collections
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
shaziabibi5
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
mcollison
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
ifis
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
jagriti srivastava
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
rangariprajwal4554
 
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdfCGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
RosaGomezCano
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Collections
CollectionsCollections
Collections
bsurya1989
 
Collections in java
Collections in javaCollections in java
Collections in javakejpretkopet
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Collection
CollectionCollection
Collection
Gayathri Ganesh
 

Similar to Java 103 (20)

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
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Data Structure Lec #1
Data Structure Lec #1Data Structure Lec #1
Data Structure Lec #1
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.ppt
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
Data structure and algorithm with java by shikra
Data structure and algorithm  with java by shikraData structure and algorithm  with java by shikra
Data structure and algorithm with java by shikra
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
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
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
Collections
CollectionsCollections
Collections
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdfCGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collection
CollectionCollection
Collection
 

Recently uploaded

Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 

Recently uploaded (20)

Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 

Java 103

  • 1. Java 103: Intro to Java Data Structures
  • 2. Introduction • Your Name: Manuela Grindei • Your day job: Software Developer @ Gamesys • Your last holiday destination: Vienna
  • 3. Java 103 • Data Structures – Arrays – Java Collections Framework – Collection Algorithms
  • 4. Java 103: Intro to Java Data Structures Arrays
  • 5. Arrays • Indexed sequence of values of the same type • Store and manipulate huge quantities of data • Examples: – 52 playing cards in a deck – Thousand undergrads at Hult – 1 million characters in a book – 10 million audio samples in an MP3 file – 4 billion nucleotides in a DNA strand – 73 billion Google queries per year – 50 trillion cells in the human body – 6.02 x 10e23 particles in a mole
  • 6. Many Variables of the Same Type • Example: Goal is to store 10 variables of the same type without Arrays
  • 7. Many Variables of the Same Type • Example: Goal is to store 10 variables of the same type Arrays
  • 8. Arrays in Java • Java has special language support for arrays – To make an array: declare, create, and initialize it – To access element i of array named a, use a[i] – Array indices start at 0 and end at a.length - 1 • Compact alternative – Declare, create, and initialize in one statement – Default initialization: all numbers automatically set to zero
  • 10. Two-Dimensional Arrays • Examples – Table of data for each experiment and outcome – Table of grades for each student and assignments – Table of gray scale values for each pixel in a 2D image • Mathematical abstraction – Matrix • Java abstraction – 2D array
  • 11. Two-Dimensional Arrays in Java • Array Access – Use a[i][j] to access element in row i and column j – Zero-based indexing – Row and column indices start at 0
  • 12. Setting Array Values at Compile Time • Initialize 2D array by listing values
  • 13. Arrays Summary • Organized way to store huge quantities of data • Almost as easy to use as primitive types • Can directly access an element given its index
  • 15. Exercise: Array of Days • Create a new Java project in Eclipse named ArrayOfDays • Create a java class named DayPrinter that prints out names of the days in a week from an array.
  • 16. Solution : Arrays of Days public class DayPrinter { public static void main(String[] args) { //initialise the array with the names of days of the week String[] daysOfTheWeek = {"Sunday","Monday","Tuesday","Wednesday", "Thuesday","Friday”,"Saturday"}; //loop through the array and print their elements to //stdout for (int i= 0;i < daysOfTheWeek.length;i++ ){ System.out.println(daysOfTheWeek[i]); } } } % javac DayPrinter.java % java DayPrinter Sunday Monday Tuesday Wednesday Thuesday Friday Saturday
  • 17. Java 103: Intro to Java Data Structures Java Collections Framework
  • 18. What is a Collection? • An object that groups multiple items into a single unit • Used to store, retrieve, manipulate, and communicate aggregate data • Represent data items that form a natural group, – a poker hand (a collection of cards) – a mail folder (a collection of letters) – a telephone directory (a mapping of names to phone numbers)
  • 19. Collections Framework • A unified architecture for representing and manipulating collections • Usually contain… – Interfaces – Implementations – Algorithms • Examples of collections frameworks in other languages – C++ Standard Template Library (STL) – Smalltalk's collection hierarchy
  • 20. Java Collections Framework • Interfaces Collection List Set Iterable SortedSet Dequeue Queue NavigableSet NavigableMap SortedMap Map Note: Map does not extend Collection; but it is a “collection”
  • 21. Collection Interface • Contains about a dozen methods that describe common operations on groups of objects • Commonly Used Methods – add(Object x) adds x to the collection – remove(Object x) removes x from the collection – contains(Object x) returns true if x is in collection – size () return number of elements – toArray() returns an array containing elements – iterator() returns an Iterator object for accessing the elements
  • 23. Exercise: Dumping Collection Elements • What happens when you run the following program? import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class DumpCollection { public static void main(String[] args) { Collection days= Arrays.asList(”Mon",”Tues",”Wed",”Thurs",”Fri",”Sat", ”Sun"); dumpCollection(days); } public static void dumpCollection(Collection c){ System.out.println("collection has " + c.size() + " elements"); Iterator iterator = c.iterator(); while (iterator.hasNext()){ System.out.println("Next element is " + iterator.next()); } } }
  • 24. List Interface • Keeps its elements in the order in which they are added • Each element has an index starting from 0 (similar to an array) • Commonly Used Methods – add (int index, Object x) insert x at index – get (int index) returns the element at index – indexOf(Object x) returns the index of the first occurrance of x – remove (int index) removes the element at index
  • 27. List World List ArrayList LinkedList Fast iteration and fast random access Good for adding elements to the ends, i.e. stacks and queues
  • 29. Exercise: Simple TODO List • Create a Java project in Eclipse named SimpleTodoList • Create a Java program named SimpleTodoList • Create a List to store your todo list items (use either ArrayList or LinkedList) • Use a for-loop to display your list contents
  • 30. Solution: Simple TODO List import java.util.ArrayList; public class SimpleTodoList { public static void main(String[] args) { ArrayList<String> todoList = new ArrayList<String>(); todoList.add("make breakfast"); todoList.add("read morning paper"); todoList.add("Doctors appointment"); for (String item : todoList ) { System.out.println("Item:" + item) ; } } }
  • 31. Set Interface • Sets contain an unordered list of elements • They do not allow duplicate elements • Commonly Used Methods – add (Object x) returns true if x doesn’t already exist and false if it exists
  • 33. Set World Set HashSet LinkedHashSet TreeSet Fast access, assures no duplicates, provides no ordering
  • 34. Set World Set HashSet LinkedHashSet TreeSet Fast access, assures no duplicates, provides no ordering No duplicates; iterates by insertion order No duplicates; iterates by insertion order
  • 35. Set World Set HashSet LinkedHashSet TreeSet Fast access, assures no duplicates, provides no ordering No duplicates; iterates by insertion order No duplicates; iterates in sorted order
  • 37. Example: Set of Points • What happens when you run the following program? import java.awt.Point; import java.util.HashSet; import java.util.Set; public class AddTwice { public static void main(String[] args) { Set points = new HashSet(); Point p1 = new Point(10,20); Point p2 = new Point(10,20); points.add(p1); points.add(p2); System.out.println("number of points = " + points.size()); } }
  • 38. Map Interface • Combines two collections called keys and values • Associates exactly one value with each key • Keys are used to get values from Maps • Commonly Used Methods – put (Object key, Object value) associates a key and a value – get(Object key) returns the value associated with key – containsKey (Object key) return true if the Map associates some value with key – keySet() returns a Set containing the Map’s keys – values() returns a Collection containing the Map’s values
  • 40. Map World Map LinkedHashMap TreeMap HashMap Fastest updates (key/values); allows one null key, many null values
  • 41. Map World Map LinkedHashMap TreeMap Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values HashMap Fastest updates (key/values); allows one null key, many null values
  • 42. Map World Map LinkedHashMap TreeMap Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values A sorted map HashMap Fastest updates (key/values); allows one null key, many null values
  • 44. Example: Word Frequency Table import java.util.*; /** * Creates a word frequency table from command line arguments */ public class WordFrequency { public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>(); for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); } } % java WordFrequency if it is to be it is up to me to delegate 8 distinct words: {to=3, is=2, it=2, if=1, me=1, delegate=1, up=1, be=1}
  • 45. Collection Framework Summary • Reduces programming effort • Increases program speed and quality • Allows interoperability among unrelated APIs • Reduces effort to learn and to use new APIs • Reduces effort to design new APIs • Fosters software reuse
  • 46. Key Methods in List, Set, and Map Key Interface Methods List Set Map Descriptions boolean add(element) boolean add(index, element) X X X Add an element. For Lists, optionally add the element at an index point boolean contains(object) boolean containsKey(object key) boolean containsValue(object value) X X X X Search a collection for an object (or, optionally for Maps a key), return the result as a boolean object get(index) object get(key) X X Get an object from a collection, via an index or a key int indexOf(object) X Get the location of an object in a List Iterator iterator() X X Get an Iterator for a List or a Set Set keySet() X Return a Set containing a Map’s keys put(key, value) X Add a key/value pair to a Map remove(index) remove(object) remove(key) X X X X Remove an element via an index, or via the element’s value, or via a key int size() X X X Return the number of elements in a collection Object[] toArray() X X Return an array containing the
  • 47. Java 103: Intro to Java Collections Collection Algorithms
  • 48. Collection Algorithms • Arrays Class – Contains static methods for operations on Arrays – Commonly Used Methods • asList(Array array) • sort (Array array) • Collections Class – Contains static methods for operations on Collections – Commonly Used Methods • sort (List list) • binarySearch(List list, Object key)
  • 50. Example: Sorting Arrays import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArraySort { public static void main(String[] args) { String[] months = {"Jan","Feb","Mar","Apr","May","June", "July", "Aug", "Sept","Oct","Nov","Dec"}; Arrays.sort(months); for (Object month :months){ System.out.println(month); } } } % java ArraySort Aug Dec Feb Jan July June Mar May Nov Oct Sept
  • 51. Example: Sorting Collections import java.util.Arrays; import java.util.Collections; import java.util.List; public class CollectionSort { public static void main(String[] args) { List months = Arrays.asList("Jan","Feb","Mar","Apr","May","June", "July", "Aug", "Sept","Oct","Nov","Dec"); Collections.sort(months); for (Object month :months){ System.out.println(month); } } } % java CollectionSort Aug Dec Feb Jan July June Mar May Nov Oct Sept
  • 52. Collection Algorithms Summary • Collection algorithms enable sorting and searching of collections • Most algorithms are in … – java.util.Collections – java.utils.Arrays
  • 53. Resources • Collections Framework Tutorial: http://docs.oracle.com/javase/tutorial/collections/ • Official Java Collections Framework Documentation: http://docs.oracle.com/javase/8/docs/technotes/guides/collections/