Aj unit2 notesjavadatastructures

Arthik Daniel
Arthik DanielAssistant Professor um Saveetha University

Java Data Structures

UNIT II - JAVA DATA STRUCTURES
Lists
Linear Structures
Arrays
Stack
Queue
Linked List
Ordered & Unordered Structures
Order Structure
Un Ordered Structure
Sorting
Trees
Binary Tree
Example of a binary tree
Operations
Implementations
Binary Search Tree (BST)
.
Lists
Collections API Revisit?
List Abstract Data Type (ADT)
• A list a collection of items in which the items have a position
• We keep “to-do” lists, shop with a grocery list, and invite a list of friends to a party
• Types of Lists
– Ordered Lists - (implements Comparable Interface)
• An ordered list is kept in order based on characteristics of the elements in the list, e.g.
alphabetical order for names
– Unordered Lists
• They are stored in an order that is externally controlled by how and when the elements are
added to the list
– Indexed Lists
Topics Discussed in URL:
● List Implementations
● Adding and Accessing Elements
● Removing Elements
● Generic Lists
A List represents a data structure which allows to dynamically add, access and remove objects of the same type. Adding objects to the
list is usually done via the add() method. The get(int i) method allows to retrieve the element at position i. Remove objects from the
list is usually done via the remove(int i) method which removes the element at position i.
Below is a sample program that explains the following:
● Custom List Implementation (using Arrays) which allows Adding, Accessing & Removing Elements
● Test Application that uses the above Customized List
MyList.java
package list;
import java.util.Arrays;
import java.util.Iterator;
/**
* Created by user on 2/15/14.
*/
public class MyList<E> {
private int size = 0;
private static final int DEFAULT_CAPACITY = 10;
private Object elements[];
public MyList() {
elements = new Object[DEFAULT_CAPACITY];
}
public void add(E e) {
if (size == elements.length) {
ensureCapa();
}
elements[size++] = e;
}
private void ensureCapa() {
int newSize = elements.length * 2;
elements = Arrays.copyOf(elements, newSize);
}
@SuppressWarnings("unchecked")
public E get(int i) {
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i);
}
return (E) elements[i];
}
public E remove(int i) {
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i);
}
size++;
E oldValue = (E) elements[i];
int numMoved = size - i - 1;
if (numMoved > 0)
System.arraycopy(elements, i + 1, elements, i, numMoved);
elements[--size] = null;
return oldValue;
}
@Override
public String toString() {
String temp = new String();
temp = "[";
for (int i = 0; i < elements.length; i++) {
if (elements[i] != null)
temp = temp + " "+ (E) elements[i] ;
}
temp = temp + "]";
return temp;
}
}
The following show contains a small test for the data structure. I use in the first test the MyList implementation and in the second test
the standard Java List implementation.
MyMainListTest.java
package list;
import com.sun.org.apache.xpath.internal.SourceTree;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 2/15/14.
*/
public class MyMainListTest {
public static void main(String[] args) {
MyMainListTest myMainListTest = new MyMainListTest();
System.out.println("Testing MyList");
try {
myMainListTest.testMyList();
} catch (Exception e) {
System.out.println("MyList " + e);
}
System.out.println("Testing StandardList");
try {
myMainListTest.testStandardList();
} catch (Exception e) {
System.out.println("StandardList " + e);
}
}
public void testMyList() {
MyList<Integer> list = new MyList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
System.out.println(list);
//Remove element on 4th Index.
list.remove(4);
System.out.println(list);
System.out.println(list.get(1));
System.out.println(list.get(6));
System.out.println(list.get(20));//Throws IndexOutOfBoundsException
System.out.println(list.get(-1));//Throws IndexOutOfBoundsException
}
public void testStandardList() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
System.out.println(list);
//Remove element on 4th Index.
list.remove(4);
System.out.println(list);
System.out.println(list.get(1));
System.out.println(list.get(6));
System.out.println(list.get(20));//Throws IndexOutOfBoundsException
System.out.println(list.get(-1));//Throws IndexOutOfBoundsException
}
}
Linear Structures
Arrays
Arrays are special data types that let us store specified number of variables from the same type using one variable
name.
An array is a sequence of data item of homogeneous value(same type).
Why Arrays?
Imagine the situation that you need to store 20 names of students as strings and 20 integers as marks, then you need to
define 40 variables, and this is clearly very hard and not practical, in such case you need to use arrays.
Arrays are indexed data types.
As Figure shows, the size of an array is fixed, we will refer to array maximum size as array length , it is also clear that
indices of an array are zero-based, that is, they start from 0 to length – 1;for example, the array shown in Figure has a
length of 10 (stores up to 10 elements), and the last index is 9
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays
One-Dimensional Arrays
● Declaration
● Initialization (Construction)
● Accessing Elements (Read / Write)
Multidimensional Arrays (Arrays of Arrays)
● Declaration
● Initialization (Construction)
● Accessing Elements (Read / Write)
http://www.tutorialspoint.com/java/util/arraylist_get.htm
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
}
public Employee(String ename, double sal) {
EmpID = i++;
Ename = ename;
Sal = sal;
}
public String toString() {
return "EmpID " + EmpID + "n" + "Ename " + Ename + "n" + "Sal" + Sal;
}
public int compareTo(Object o1) {
if (this.Sal == ((Employee) o1).Sal)
return 0;
else if ((this.Sal) > ((Employee) o1).Sal)
return 1;
else
return -1;
}
}
ComparableDemo.java
import java.util.*;
public class ComparableDemo{
public static void main(String[] args) {
List ts1 = new ArrayList();
ts1.add(new Employee ("Tom",40000.00));
ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));
ts1.add(new Employee ("Chris",70000.00));
Collections.sort(ts1);
Iterator itr = ts1.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "n");
}
}
}
Output:
EmpID 1
Ename Harry
Sal20000.0
EmpID 0
Ename Tom
Sal40000.0
EmpID 2
Ename Maggie
Sal50000.0
EmpID 3
Ename Chris
Sal70000.0
http://math.hws.edu/javanotes/c7/index.html
http://math.hws.edu/javanotes/c7/s3.html
http://math.hws.edu/javanotes/c7/s5.html
Stack
Stack Implementation using Arrays
http://www.vogella.com/tutorials/JavaDatastructures/article.html
http://www.youtube.com/watch?v=sFVxsglODoo
http://www.studytonight.com/data-structures/stack-data-structure
http://tutorials.jenkov.com/java-collections/stack.html
http://math.hws.edu/javanotes/c9/s3.html
Queue
Queue Implementation using Arrays
http://www.youtube.com/watch?v=okr-XE8yTO8
http://www.studytonight.com/data-structures/queue-data-structure
http://tutorials.jenkov.com/java-collections/queue.html
http://math.hws.edu/javanotes/c9/s3.html
Linked List
- Insert at Head
- Insert at Last (Append)
- Insert Middle Element
- Insert After Element
- Insert Before Element
- Delete Head
- Delete Last Element
- Delete Middle Element
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html
http://www.idevelopment.info/data/Programming/data_structures/java/LinkedList/LinkedList.shtml
http://math.hws.edu/javanotes/c9/s2.html
http://www.tutorialspoint.com/java/java_linkedlist_class.htm
Ordered & Unordered Structures
Order Structure
List--an ordered collection, duplicates are allowed. Topic already discussed earlier.
Below are the 4 possible implementations of List.
List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();
http://tutorials.jenkov.com/java-collections/list.html
Un Ordered Structure
Set--An unordered collection with no duplicates.
Below are the 4 possible implementations of Set.
Set setA = new EnumSet();
Set setB = new HashSet();
Set setC = new LinkedHashSet();
Set setD = new TreeSet();
http://tutorials.jenkov.com/java-collections/set.html
http://www.vogella.com/tutorials/JavaDatastructures/article.html
Sorting
General Explanation for Various Sorting Algorithms:
Bubble Sort
http://www.youtube.com/watch?v=8Kp-8OGwphY
Selection Sort:
http://www.youtube.com/watch?v=f8hXR_Hvybo
Insertion Sort:
http://www.youtube.com/watch?v=DFG-XuyPYUQ
Merge Sort:
http://www.youtube.com/watch?v=EeQ8pwjQxTM
Student Assignment: Lab programs on various Sorting Algorithms (Thursday Lab HR)
Unit 2 question bNk 16 mark notes submission (Friday by EOD)
Source Code for Sorting Algorithms
Bubble Sort
http://www.algolist.net/Algorithms/Sorting/Bubble_sort
http://www.sorting-algorithms.com/bubble-sort
Selection Sort:
http://www.youtube.com/watch?v=f8hXR_Hvybo
http://www.algolist.net/Algorithms/Sorting/Selection_sort
http://www.sorting-algorithms.com/selection-sort
Merge Sort:
http://www.youtube.com/watch?v=EeQ8pwjQxTM
http://www.algolist.net/Algorithms/Merge/Sorted_arrays
http://www.sorting-algorithms.com/merge-sort
Insertion Sort:
http://www.youtube.com/watch?v=DFG-XuyPYUQ
http://www.algolist.net/Algorithms/Sorting/Insertion_sort
http://www.sorting-algorithms.com/insertion-sort
Trees
Binary Tree
Binary tree is a widely-used tree data structure. Feature of a binary tree, which distinguish it from
common tree, is that each node has at most two children. Each binary tree has following groups of
nodes:
● Root: the topmost node in a tree. It is a kind of "main node" in the tree, because all other nodes
can be reached from root. Also, root has no parent. It is the node, at which operations on tree
begin (commonly).
● Internal nodes: these nodes has a parent (root node is not an internal node) and at least one child.
● Leaf nodes: these nodes has a parent, but has no children.
Example of a binary tree
Operations
Basically, we can only define traversals for binary tree as possible operations: root-left-right
(preorder), left-right-root (postorder) and left-root-right (inorder) traversals. We will speak about them
in detail later.
Implementations
● Binary Search Tree (BST)
Binary Search Tree (BST)
General Idea of Trees:
http://www.youtube.com/watch?v=rSlFhunlpzI
Source Code for Binary Search Tree
http://www.youtube.com/watch?v=M6lYob8STMI
http://www.youtube.com/watch?v=UcOxGmj45AA
public class BinaryTree {
Node root;
public void addNode(int key, String name) {
// Create a new Node and initialize it
Node newNode = new Node(key, name);
// If there is no root this becomes root
if (root == null) {
root = newNode;
} else {
// Set root as the Node we will start
// with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while (true) {
// root is the top parent so we start
// there
parent = focusNode;
// Check if the new node should go on
// the left side of the parent node
if (key < focusNode.key) {
// Switch focus to the left child
focusNode = focusNode.leftChild;
// If the left child has no children
if (focusNode == null) {
// then place the new node on the left of it
parent.leftChild = newNode;
return; // All Done
}
} else { // If we get here put the node on the right
focusNode = focusNode.rightChild;
// If the right child has no children
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
// All nodes are visited in ascending order
// Recursion is used to go to one node and
// then go to its child nodes and so forth
public void inOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
// Traverse the left node
inOrderTraverseTree(focusNode.leftChild);
// Visit the currently focused on node
System.out.println(focusNode);
// Traverse the right node
inOrderTraverseTree(focusNode.rightChild);
}
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.leftChild);
preorderTraverseTree(focusNode.rightChild);
}
}
public void postOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
}
}
public Node findNode(int key) {
// Start at the top of the tree
Node focusNode = root;
// While we haven't found the Node
// keep looking
while (focusNode.key != key) {
// If we should search to the left
if (key < focusNode.key) {
// Shift the focus Node to the left child
focusNode = focusNode.leftChild;
} else {
// Shift the focus Node to the right child
focusNode = focusNode.rightChild;
}
// The node wasn't found
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args) {
BinaryTree theTree = new BinaryTree();
theTree.addNode(50, "Boss");
theTree.addNode(25, "Vice President");
theTree.addNode(15, "Office Manager");
theTree.addNode(30, "Secretary");
theTree.addNode(75, "Sales Manager");
theTree.addNode(85, "Salesman 1");
// Different ways to traverse binary trees
// theTree.inOrderTraverseTree(theTree.root);
// theTree.preorderTraverseTree(theTree.root);
// theTree.postOrderTraverseTree(theTree.root);
// Find the node with key 75
System.out.println("nNode with the key 75");
System.out.println(theTree.findNode(75));
}
}
class Node {
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return name + " has the key " + key;
/*
* return name + " has the key " + key + "nLeft Child: " + leftChild +
* "nRight Child: " + rightChild + "n";
*/
}
}

Recomendados

An Introduction to Programming in Java: Arrays von
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysMartin Chapman
1.4K views59 Folien
Lec 25 - arrays-strings von
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
2.5K views44 Folien
Array in Java von
Array in JavaArray in Java
Array in JavaShehrevar Davierwala
3K views71 Folien
Arrays in Java von
Arrays in JavaArrays in Java
Arrays in JavaAbhilash Nair
24.1K views24 Folien
Python array von
Python arrayPython array
Python arrayArnab Chakraborty
179 views19 Folien
Arrays in python von
Arrays in pythonArrays in python
Arrays in pythonLifna C.S
1.5K views20 Folien

Más contenido relacionado

Was ist angesagt?

Data structures in c# von
Data structures in c#Data structures in c#
Data structures in c#SivaSankar Gorantla
2.1K views48 Folien
Arrays In Python | Python Array Operations | Edureka von
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
3.6K views30 Folien
Java Arrays von
Java ArraysJava Arrays
Java ArraysJussi Pohjolainen
7.9K views18 Folien
Array properties von
Array propertiesArray properties
Array propertiesShravan Sharma
450 views39 Folien
Java arrays von
Java arraysJava arrays
Java arraysBHUVIJAYAVELU
3.2K views6 Folien

Was ist angesagt?(20)

Arrays In Python | Python Array Operations | Edureka von Edureka!
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!3.6K views
9781439035665 ppt ch09 von Terry Yoast
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast844 views
Arrays in python von moazamali28
Arrays in pythonArrays in python
Arrays in python
moazamali283.3K views
arrays-120712074248-phpapp01 von Abdul Samee
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee147 views
Set data structure von Tech_MX
Set data structure Set data structure
Set data structure
Tech_MX24.8K views
Java arrays von Jin Castor
Java arraysJava arrays
Java arrays
Jin Castor1.4K views
Java10 Collections and Information von SoftNutx
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx295 views
Array in Java von Ali shah
Array in JavaArray in Java
Array in Java
Ali shah485 views

Destacado

cblm-java-prog-ds von
cblm-java-prog-dscblm-java-prog-ds
cblm-java-prog-dsJohndion Ruloma
847 views46 Folien
Linked list (java platform se 8 ) von
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )charan kumar
325 views23 Folien
Data structures von
Data structuresData structures
Data structuresNaresh Babu Merugu
1.4K views242 Folien
Stacks,queues,linked-list von
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
1.6K views18 Folien
Final ds record von
Final ds recordFinal ds record
Final ds recordGanisius Ganish
1K views78 Folien
Data structures and algorithms made easy java von
Data structures and algorithms made easy   javaData structures and algorithms made easy   java
Data structures and algorithms made easy javaCareerMonk Publications
8.9K views15 Folien

Destacado(20)

Linked list (java platform se 8 ) von charan kumar
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
charan kumar325 views
Stacks,queues,linked-list von pinakspatel
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel1.6K views
Ime newsletter4 von royc1
Ime newsletter4Ime newsletter4
Ime newsletter4
royc11.9K views
Evolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid von MEC_Hungary
Evolution 2016 - Programmatic a márkakampányokban - Ihász IngridEvolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
Evolution 2016 - Programmatic a márkakampányokban - Ihász Ingrid
MEC_Hungary241 views
Harris Ait Presentation von rogerharris
Harris Ait PresentationHarris Ait Presentation
Harris Ait Presentation
rogerharris395 views
A YouTube szerepe a médiamixben workshop - Jobbágy Tamás előadása von MEC_Hungary
A YouTube szerepe a médiamixben workshop -  Jobbágy Tamás előadásaA YouTube szerepe a médiamixben workshop -  Jobbágy Tamás előadása
A YouTube szerepe a médiamixben workshop - Jobbágy Tamás előadása
MEC_Hungary628 views
IH 2015 - Változó idők, változó szerepek - Gulyás János von MEC_Hungary
IH 2015 - Változó idők, változó szerepek - Gulyás JánosIH 2015 - Változó idők, változó szerepek - Gulyás János
IH 2015 - Változó idők, változó szerepek - Gulyás János
MEC_Hungary218 views
Social and digital media digital yearbook 2011 Adma von Juan Sanchez Bonet
Social and digital media digital yearbook 2011 AdmaSocial and digital media digital yearbook 2011 Adma
Social and digital media digital yearbook 2011 Adma
Juan Sanchez Bonet4.4K views
Commendation of Service Excellence - Maybank Alan Lau von Nathaniel Han
Commendation of Service Excellence - Maybank Alan LauCommendation of Service Excellence - Maybank Alan Lau
Commendation of Service Excellence - Maybank Alan Lau
Nathaniel Han193 views
Internationalization in java von Arthik Daniel
Internationalization in javaInternationalization in java
Internationalization in java
Arthik Daniel749 views

Similar a Aj unit2 notesjavadatastructures

Chap09 von
Chap09Chap09
Chap09Terry Yoast
688 views77 Folien
Basic data-structures-v.1.1 von
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1BG Java EE Course
5.3K views78 Folien
16. Arrays Lists Stacks Queues von
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
30.2K views50 Folien
JavaScript.pptx von
JavaScript.pptxJavaScript.pptx
JavaScript.pptxpramod599939
3 views13 Folien
02 Arrays And Memory Mapping von
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
6K views24 Folien
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE von
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
130 views6 Folien

Similar a Aj unit2 notesjavadatastructures(20)

16. Arrays Lists Stacks Queues von Intro C# Book
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book30.2K views
02 Arrays And Memory Mapping von Qundeel
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
Qundeel6K views
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE von Dev Chauhan
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
Dev Chauhan130 views
Java ArrayList Tutorial | Edureka von Edureka!
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
Edureka!1.1K views
Data Structure In C# von Shahzad
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad 28K views
16 Linear data structures von maznabili
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili448 views
Engineering lecture ppt by venay magen von venaymagen19
Engineering lecture ppt by venay magenEngineering lecture ppt by venay magen
Engineering lecture ppt by venay magen
venaymagen19213 views
lec6.ppt von cawarir
lec6.pptlec6.ppt
lec6.ppt
cawarir3 views
DSA UNIT II ARRAY AND LIST - notes von swathirajstar
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
swathirajstar64 views
Collections von sagsharma
CollectionsCollections
Collections
sagsharma178 views
Lecture_3.5-Array_Type Conversion_Math Class.pptx von ShahinAhmed49
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
ShahinAhmed494 views

Último

NTGapps NTG LowCode Platform von
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform Mustafa Kuğu
437 views30 Folien
Digital Personal Data Protection (DPDP) Practical Approach For CISOs von
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOsPriyanka Aash
162 views59 Folien
MVP and prioritization.pdf von
MVP and prioritization.pdfMVP and prioritization.pdf
MVP and prioritization.pdfrahuldharwal141
39 views8 Folien
Initiating and Advancing Your Strategic GIS Governance Strategy von
Initiating and Advancing Your Strategic GIS Governance StrategyInitiating and Advancing Your Strategic GIS Governance Strategy
Initiating and Advancing Your Strategic GIS Governance StrategySafe Software
184 views68 Folien
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue von
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueShapeBlue
207 views54 Folien
Generative AI: Shifting the AI Landscape von
Generative AI: Shifting the AI LandscapeGenerative AI: Shifting the AI Landscape
Generative AI: Shifting the AI LandscapeDeakin University
67 views55 Folien

Último(20)

NTGapps NTG LowCode Platform von Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu437 views
Digital Personal Data Protection (DPDP) Practical Approach For CISOs von Priyanka Aash
Digital Personal Data Protection (DPDP) Practical Approach For CISOsDigital Personal Data Protection (DPDP) Practical Approach For CISOs
Digital Personal Data Protection (DPDP) Practical Approach For CISOs
Priyanka Aash162 views
Initiating and Advancing Your Strategic GIS Governance Strategy von Safe Software
Initiating and Advancing Your Strategic GIS Governance StrategyInitiating and Advancing Your Strategic GIS Governance Strategy
Initiating and Advancing Your Strategic GIS Governance Strategy
Safe Software184 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue von ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue207 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue von ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue265 views
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ... von ShapeBlue
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
ShapeBlue129 views
The Role of Patterns in the Era of Large Language Models von Yunyao Li
The Role of Patterns in the Era of Large Language ModelsThe Role of Patterns in the Era of Large Language Models
The Role of Patterns in the Era of Large Language Models
Yunyao Li91 views
"Node.js Development in 2024: trends and tools", Nikita Galkin von Fwdays
"Node.js Development in 2024: trends and tools", Nikita Galkin "Node.js Development in 2024: trends and tools", Nikita Galkin
"Node.js Development in 2024: trends and tools", Nikita Galkin
Fwdays33 views
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue von ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
ShapeBlue152 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... von ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue120 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... von ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue199 views
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... von ShapeBlue
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
ShapeBlue108 views
Future of AR - Facebook Presentation von Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty65 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... von ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue164 views
"Running students' code in isolation. The hard way", Yurii Holiuk von Fwdays
"Running students' code in isolation. The hard way", Yurii Holiuk "Running students' code in isolation. The hard way", Yurii Holiuk
"Running students' code in isolation. The hard way", Yurii Holiuk
Fwdays36 views
LLMs in Production: Tooling, Process, and Team Structure von Aggregage
LLMs in Production: Tooling, Process, and Team StructureLLMs in Production: Tooling, Process, and Team Structure
LLMs in Production: Tooling, Process, and Team Structure
Aggregage57 views
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT von ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue208 views

Aj unit2 notesjavadatastructures

  • 1. UNIT II - JAVA DATA STRUCTURES Lists Linear Structures Arrays Stack Queue Linked List Ordered & Unordered Structures Order Structure Un Ordered Structure Sorting Trees Binary Tree Example of a binary tree Operations Implementations Binary Search Tree (BST) .
  • 2. Lists Collections API Revisit? List Abstract Data Type (ADT) • A list a collection of items in which the items have a position • We keep “to-do” lists, shop with a grocery list, and invite a list of friends to a party • Types of Lists – Ordered Lists - (implements Comparable Interface) • An ordered list is kept in order based on characteristics of the elements in the list, e.g. alphabetical order for names – Unordered Lists • They are stored in an order that is externally controlled by how and when the elements are added to the list – Indexed Lists Topics Discussed in URL: ● List Implementations ● Adding and Accessing Elements ● Removing Elements ● Generic Lists A List represents a data structure which allows to dynamically add, access and remove objects of the same type. Adding objects to the list is usually done via the add() method. The get(int i) method allows to retrieve the element at position i. Remove objects from the list is usually done via the remove(int i) method which removes the element at position i. Below is a sample program that explains the following: ● Custom List Implementation (using Arrays) which allows Adding, Accessing & Removing Elements ● Test Application that uses the above Customized List
  • 3. MyList.java package list; import java.util.Arrays; import java.util.Iterator; /** * Created by user on 2/15/14. */ public class MyList<E> { private int size = 0; private static final int DEFAULT_CAPACITY = 10; private Object elements[]; public MyList() { elements = new Object[DEFAULT_CAPACITY]; } public void add(E e) { if (size == elements.length) { ensureCapa(); } elements[size++] = e; } private void ensureCapa() { int newSize = elements.length * 2; elements = Arrays.copyOf(elements, newSize); } @SuppressWarnings("unchecked") public E get(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } return (E) elements[i]; } public E remove(int i) { if (i >= size || i < 0) { throw new IndexOutOfBoundsException("Index: " + i + ", Size " + i); } size++; E oldValue = (E) elements[i]; int numMoved = size - i - 1; if (numMoved > 0) System.arraycopy(elements, i + 1, elements, i, numMoved); elements[--size] = null; return oldValue; } @Override public String toString() { String temp = new String(); temp = "["; for (int i = 0; i < elements.length; i++) { if (elements[i] != null) temp = temp + " "+ (E) elements[i] ; }
  • 4. temp = temp + "]"; return temp; } } The following show contains a small test for the data structure. I use in the first test the MyList implementation and in the second test the standard Java List implementation. MyMainListTest.java package list; import com.sun.org.apache.xpath.internal.SourceTree; import java.util.ArrayList; import java.util.List; /** * Created by user on 2/15/14. */ public class MyMainListTest { public static void main(String[] args) { MyMainListTest myMainListTest = new MyMainListTest(); System.out.println("Testing MyList"); try { myMainListTest.testMyList(); } catch (Exception e) { System.out.println("MyList " + e); } System.out.println("Testing StandardList"); try { myMainListTest.testStandardList(); } catch (Exception e) { System.out.println("StandardList " + e); } } public void testMyList() { MyList<Integer> list = new MyList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); System.out.println(list); //Remove element on 4th Index. list.remove(4); System.out.println(list); System.out.println(list.get(1));
  • 5. System.out.println(list.get(6)); System.out.println(list.get(20));//Throws IndexOutOfBoundsException System.out.println(list.get(-1));//Throws IndexOutOfBoundsException } public void testStandardList() { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); list.add(2); list.add(3); list.add(3); list.add(4); System.out.println(list); //Remove element on 4th Index. list.remove(4); System.out.println(list); System.out.println(list.get(1)); System.out.println(list.get(6)); System.out.println(list.get(20));//Throws IndexOutOfBoundsException System.out.println(list.get(-1));//Throws IndexOutOfBoundsException } }
  • 6. Linear Structures Arrays Arrays are special data types that let us store specified number of variables from the same type using one variable name. An array is a sequence of data item of homogeneous value(same type). Why Arrays? Imagine the situation that you need to store 20 names of students as strings and 20 integers as marks, then you need to define 40 variables, and this is clearly very hard and not practical, in such case you need to use arrays. Arrays are indexed data types. As Figure shows, the size of an array is fixed, we will refer to array maximum size as array length , it is also clear that indices of an array are zero-based, that is, they start from 0 to length – 1;for example, the array shown in Figure has a length of 10 (stores up to 10 elements), and the last index is 9 Arrays are of two types: 1. One-dimensional arrays 2. Multidimensional arrays One-Dimensional Arrays ● Declaration ● Initialization (Construction) ● Accessing Elements (Read / Write) Multidimensional Arrays (Arrays of Arrays) ● Declaration ● Initialization (Construction) ● Accessing Elements (Read / Write)
  • 7. http://www.tutorialspoint.com/java/util/arraylist_get.htm Employee.java public class Employee implements Comparable { int EmpID; String Ename; double Sal; static int i; public Employee() { EmpID = i++; Ename = "dont know"; Sal = 0.0; } public Employee(String ename, double sal) { EmpID = i++; Ename = ename; Sal = sal; } public String toString() { return "EmpID " + EmpID + "n" + "Ename " + Ename + "n" + "Sal" + Sal; } public int compareTo(Object o1) { if (this.Sal == ((Employee) o1).Sal) return 0; else if ((this.Sal) > ((Employee) o1).Sal) return 1; else return -1; } } ComparableDemo.java import java.util.*; public class ComparableDemo{ public static void main(String[] args) { List ts1 = new ArrayList(); ts1.add(new Employee ("Tom",40000.00)); ts1.add(new Employee ("Harry",20000.00)); ts1.add(new Employee ("Maggie",50000.00)); ts1.add(new Employee ("Chris",70000.00)); Collections.sort(ts1);
  • 8. Iterator itr = ts1.iterator(); while(itr.hasNext()){ Object element = itr.next(); System.out.println(element + "n"); } } } Output: EmpID 1 Ename Harry Sal20000.0 EmpID 0 Ename Tom Sal40000.0 EmpID 2 Ename Maggie Sal50000.0 EmpID 3 Ename Chris Sal70000.0 http://math.hws.edu/javanotes/c7/index.html http://math.hws.edu/javanotes/c7/s3.html http://math.hws.edu/javanotes/c7/s5.html Stack Stack Implementation using Arrays http://www.vogella.com/tutorials/JavaDatastructures/article.html http://www.youtube.com/watch?v=sFVxsglODoo http://www.studytonight.com/data-structures/stack-data-structure http://tutorials.jenkov.com/java-collections/stack.html http://math.hws.edu/javanotes/c9/s3.html Queue Queue Implementation using Arrays http://www.youtube.com/watch?v=okr-XE8yTO8
  • 9. http://www.studytonight.com/data-structures/queue-data-structure http://tutorials.jenkov.com/java-collections/queue.html http://math.hws.edu/javanotes/c9/s3.html Linked List - Insert at Head - Insert at Last (Append) - Insert Middle Element - Insert After Element - Insert Before Element - Delete Head - Delete Last Element - Delete Middle Element http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html http://www.idevelopment.info/data/Programming/data_structures/java/LinkedList/LinkedList.shtml http://math.hws.edu/javanotes/c9/s2.html http://www.tutorialspoint.com/java/java_linkedlist_class.htm
  • 10. Ordered & Unordered Structures Order Structure List--an ordered collection, duplicates are allowed. Topic already discussed earlier. Below are the 4 possible implementations of List. List listA = new ArrayList(); List listB = new LinkedList(); List listC = new Vector(); List listD = new Stack(); http://tutorials.jenkov.com/java-collections/list.html Un Ordered Structure Set--An unordered collection with no duplicates. Below are the 4 possible implementations of Set. Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet(); http://tutorials.jenkov.com/java-collections/set.html http://www.vogella.com/tutorials/JavaDatastructures/article.html
  • 11. Sorting General Explanation for Various Sorting Algorithms: Bubble Sort http://www.youtube.com/watch?v=8Kp-8OGwphY Selection Sort: http://www.youtube.com/watch?v=f8hXR_Hvybo Insertion Sort: http://www.youtube.com/watch?v=DFG-XuyPYUQ Merge Sort: http://www.youtube.com/watch?v=EeQ8pwjQxTM Student Assignment: Lab programs on various Sorting Algorithms (Thursday Lab HR) Unit 2 question bNk 16 mark notes submission (Friday by EOD) Source Code for Sorting Algorithms Bubble Sort http://www.algolist.net/Algorithms/Sorting/Bubble_sort http://www.sorting-algorithms.com/bubble-sort Selection Sort: http://www.youtube.com/watch?v=f8hXR_Hvybo http://www.algolist.net/Algorithms/Sorting/Selection_sort http://www.sorting-algorithms.com/selection-sort Merge Sort: http://www.youtube.com/watch?v=EeQ8pwjQxTM http://www.algolist.net/Algorithms/Merge/Sorted_arrays http://www.sorting-algorithms.com/merge-sort Insertion Sort: http://www.youtube.com/watch?v=DFG-XuyPYUQ http://www.algolist.net/Algorithms/Sorting/Insertion_sort http://www.sorting-algorithms.com/insertion-sort
  • 12. Trees Binary Tree Binary tree is a widely-used tree data structure. Feature of a binary tree, which distinguish it from common tree, is that each node has at most two children. Each binary tree has following groups of nodes: ● Root: the topmost node in a tree. It is a kind of "main node" in the tree, because all other nodes can be reached from root. Also, root has no parent. It is the node, at which operations on tree begin (commonly). ● Internal nodes: these nodes has a parent (root node is not an internal node) and at least one child. ● Leaf nodes: these nodes has a parent, but has no children. Example of a binary tree Operations Basically, we can only define traversals for binary tree as possible operations: root-left-right (preorder), left-right-root (postorder) and left-root-right (inorder) traversals. We will speak about them in detail later. Implementations ● Binary Search Tree (BST) Binary Search Tree (BST) General Idea of Trees: http://www.youtube.com/watch?v=rSlFhunlpzI Source Code for Binary Search Tree http://www.youtube.com/watch?v=M6lYob8STMI http://www.youtube.com/watch?v=UcOxGmj45AA public class BinaryTree { Node root; public void addNode(int key, String name) { // Create a new Node and initialize it Node newNode = new Node(key, name);
  • 13. // If there is no root this becomes root if (root == null) { root = newNode; } else { // Set root as the Node we will start // with as we traverse the tree Node focusNode = root; // Future parent for our new Node Node parent; while (true) { // root is the top parent so we start // there parent = focusNode; // Check if the new node should go on // the left side of the parent node if (key < focusNode.key) { // Switch focus to the left child focusNode = focusNode.leftChild; // If the left child has no children if (focusNode == null) { // then place the new node on the left of it parent.leftChild = newNode; return; // All Done } } else { // If we get here put the node on the right focusNode = focusNode.rightChild; // If the right child has no children if (focusNode == null) { // then place the new node on the right of it parent.rightChild = newNode; return; // All Done } }
  • 14. } } } // All nodes are visited in ascending order // Recursion is used to go to one node and // then go to its child nodes and so forth public void inOrderTraverseTree(Node focusNode) { if (focusNode != null) { // Traverse the left node inOrderTraverseTree(focusNode.leftChild); // Visit the currently focused on node System.out.println(focusNode); // Traverse the right node inOrderTraverseTree(focusNode.rightChild); } } public void preorderTraverseTree(Node focusNode) { if (focusNode != null) { System.out.println(focusNode); preorderTraverseTree(focusNode.leftChild); preorderTraverseTree(focusNode.rightChild); } } public void postOrderTraverseTree(Node focusNode) { if (focusNode != null) { postOrderTraverseTree(focusNode.leftChild); postOrderTraverseTree(focusNode.rightChild); System.out.println(focusNode); } } public Node findNode(int key) { // Start at the top of the tree Node focusNode = root; // While we haven't found the Node
  • 15. // keep looking while (focusNode.key != key) { // If we should search to the left if (key < focusNode.key) { // Shift the focus Node to the left child focusNode = focusNode.leftChild; } else { // Shift the focus Node to the right child focusNode = focusNode.rightChild; } // The node wasn't found if (focusNode == null) return null; } return focusNode; } public static void main(String[] args) { BinaryTree theTree = new BinaryTree(); theTree.addNode(50, "Boss"); theTree.addNode(25, "Vice President"); theTree.addNode(15, "Office Manager"); theTree.addNode(30, "Secretary"); theTree.addNode(75, "Sales Manager"); theTree.addNode(85, "Salesman 1"); // Different ways to traverse binary trees // theTree.inOrderTraverseTree(theTree.root); // theTree.preorderTraverseTree(theTree.root); // theTree.postOrderTraverseTree(theTree.root); // Find the node with key 75 System.out.println("nNode with the key 75"); System.out.println(theTree.findNode(75)); }
  • 16. } class Node { int key; String name; Node leftChild; Node rightChild; Node(int key, String name) { this.key = key; this.name = name; } public String toString() { return name + " has the key " + key; /* * return name + " has the key " + key + "nLeft Child: " + leftChild + * "nRight Child: " + rightChild + "n"; */ } }