330 likes | 357 Views
Learn about data structures and collections in computer science, including stacks, queues, lists, and trees. Understand how to implement and manipulate these data structures using Java. Discover the importance of grouping related data together for efficient programming.
E N D
Collections • Sometimes we want to group data together into collections so we can deal with related data all at once rather that each component individually. • In computing, collections are often referred to as data structures. • You must give the collection a name • There are two basic types of collections: • homogeneous: where all elements in the collection must be of the same type or class. • heterogeneous: where individual members can be of different types or classes CS 1
Collections Some examples of collections: • a group of playing cards that make up a pile in a card game • lists of names and addresses for a mailing list • parts that make up an automobile • lines of text and figures that make up a document CS 1
Data structures • For any data structure you need to be able to refer to the whole structure, and/or its individual elements. • Each data structure will also have a set of operations you want to perform on it, such as: • create a structure • add a new element • access values • make a copy • Some operations affect the entire structure, others just specific members. CS 1
Data structures • Sometimes it is important that the elements of a data structure be in some sort of order. • Ordering doesn't change the data just the way it is kept. • When performing operations on an ordered structure the order must be maintained. • Data may be ordering in • ascending order (values are increasing) • descending order (values are decreasing) • What does it mean for characters? (‘C’ < ‘c’ < ‘d’) CS 1
Data structures - other kinds of ordering • First In First Out (FIFO) • Last In First Out (LIFO) • Priority CS 1
Data Structures • Data structures permit the storage of related data for use in your program. • Dynamic data structures hold an unknown number of elements. • Arrays hold a specified number of elements. • Generic type data structures hold data elements of different data types. • Arrays hold data of the same data type. CS 1
Data Structures • Types of dynamic generic data structures are: • Stacks • Queues • Lists • Trees CS 1
What is a Stack? • A stack is similar in concept to a pile of plates, books, blocks, boxes, etc. • The first item put on the stack is on the bottom of the stack. • All items added to the stack are placed on top of the previous item. • The last item put on the stack is on the top of the stack. CS 1
Stacks • Stacks are called Last-in First-out (LIFO) data structures. • The last plate put on the top of the stack is the first plate removed from the stack. • The first plate put on the top of the stack is the last plate removed from the stack. CS 1
Characteristics of Stacks • Data can only be place on the top of the stack. • Data can only be removed from the top of the stack. • Data can only be removed from the bottom of the stack if there is only one item on the stack. • Data can not be removed from the middle of the stack without first removing all items from the top. CS 1
Stack Example Create a stack with the following information: • Place the following numbers in a stack in this order: 5, 8, 10, 2, 4, 12 • Remove number 10 from the stack. • Put 3, 7, 1 on the stack. • Now remove 5 from the bottom of the stack and put it on the top of the stack. CS 1
Stack Behaviors • new • create the stack • push • add an element to the top of the stack • pop • remove an element from the top of the stack • empty • tests if this stack is empty. • peek • looks at the object at the top of this stack without removing it from the stack CS 1
Example • What stack is exists after executing the following commands? • push(3) • push(6) • push(8) • push(1) • pop( ) • pop( ) • push(14) CS 1
Stack Implementation • Java has a Stack class designed to hold Objects. • BUT, you could implement a stack using a list, a queue, or an array. CS 1
Stack Implementation • A Stack class can be written using arrays that will simulate a stack in your programs. • A restriction of using arrays to implement a stack is that the total size of the stack is limited. • Why? • Can you define a method that will resize the array to hold a stack of any size? CS 1
Stack Implementation • Create a Stack class to hold Strings. • Assume that the first element of the array is the bottom element on the stack. • How do we know the number of items on the stack? • How do we know if there is anything in the stack? CS 1
Stack Implementation import java.io.*; class MyStack { private String [] stack; private int index; public int size; public MyStack() { this.stack = new String[10]; this.size = 10; this.index = 0; } public MyStack(int size) { stack = new String[size]; this.size = size; index = 0; } public void push(String s) { if (index < size) stack[index++] = s; else System.out.println("Overflow!!!"); } public String pop() { String r = ""; if (index > 0) r = stack[--index]; else r = “Underflow!!!"; return (r); } public boolean empty() { return (index == 0); } public String peek() { String r = ""; if (index > 0) r = stack[index-1]; return (r); } } Note: Not 100% correct. We should handle overflow and underflow better !!! CS 1
Stack Implementation • Now that we have implemented the Stack class, how can we use it? import MyStack; class MyStackTest { public static void main(String[ ] args) { MyStack s = new MyStack(); System.out.println( s.size ); s.push("a"); s.push("b"); s.push("c"); s.push("d"); System.out.println( "------------" ); while (! s.empty() ) System.out.println( s.pop() ); System.out.println( s.pop() ); // Let’s cause an underflow! } } C:\>Test\java MyStackTest 10 ------------ d c b a Underflow!!! CS 1
Stack Implementation • How do we store data of any type into our stack? CS 1
Object Class • Every class in Java is a child of the Object class. • The Object class is the most generic class in Java. • Therefore, we should be able to create a stack of type Object to store any data into the stack. • This is not strictly true. Primitive data types are not descendents of type Object. CS 1
Type Wrapper Classes • Each primitive data type has a type wrapperclass. • The type wrapper class for: • double is Double, • int is Integer, • float is Float, • boolean is Boolean. CS 1
Type Wrapper Classes • Type wrapper classes allow you to manipulate primitive data types as objects of class Object. • The type wrapper class contains functions that manipulate the data as a class. CS 1
Type Wrapper Classes • The primitive data type is not automatically a type wrapper version of the data type. • To define a version of the primitive data type as a type wrapper you need to create a new instance of the type wrapper. Integer newInteger = new Integer(98); Double newDouble = new Double(986.3); CS 1
Stack Implementation • How do we redefine our Stackclass to hold data of any data type? CS 1
Stack Implementation using Objects import java.io.*; class MyOStack { private Object [] stack; private int index; public int size; public MyOStack() { stack = new Object[10]; size = 10; index = 0; } public MyOStack(int size) { stack = new Object[size]; this.size = size; index = 0; } public void push(Object s) { if (index < size) stack[index++] = s; else System.out.println("Overflow!!!"); } public Object pop() { Object r = null; if (index > 0) r = stack[--index]; else r = Underflow!!!"; return (r); } public boolean empty() { return (index == 0); } public Object peek() { Object r = ""; if (index > 0) r = stack[index]; return (r); } } CS 1
Vectors • The Vector class implements a growable array of objects. • Like an array, it contains components that can be accessed using an integer index. • The size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. CS 1
Vectors • Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. • The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. • An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. CS 1
Vectors The Vector class is defined in this package. Adds a new element to the end of the vector This creates a vector whose internal data array has the default capacity of 10. Print vector’s last element. Reset vector’s size. import java.util. *; class VectorExample { publicstaticvoid fillVector(Vector vector) { vector.addElement(“Acura"); vector.addElement(“Audi"); vector.addElement(“BMW"); vector.addElement(“Lexus"); } publicstaticvoid main(String[] args) { Vector vector = new Vector(); if ( vector.isEmpty() ) System.out.println("Vector is empty"); fillVector(vector); System.out.println(vector.size() ); System.out.println(vector.lastElement() ); vector.setSize(3); System.out.println(vector.lastElement() ); } } CS 1
Vectors import java.util. *; class VectorExample { publicstaticvoid fillVector(Vector cars) { cars.addElement(“Acura"); cars.addElement(“Audi"); cars.addElement(“BMW"); cars.addElement(“Lexus"); } publicstaticvoid main(String[ ] args) { Vector carList = new Vector( ); if ( carList.isEmpty( ) ) System.out.println("Vector is empty"); fillVector(carList); System.out.println(carList.size( ) ); System.out.println(carList.lastElement( ) ); carList.setSize(3); System.out.println(carList.size( ) ); System.out.println(carList.lastElement( ) ); } } Output: Vector is empty 4 Lexus 3 BMW CS 1
Vector constructors Note: no type for objects is specified ! • Vector() • Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. • Vector(int initialCapacity) • Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. • Vector(int initialCapacity, int capacityIncrement) • Constructs an empty vector with the specified initial capacity and capacity increment. • Vector(Collection c) • Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator. At this time, do not bother about this one! CS 1
Vectors Type casting is required. String myCar = (String) carList.elementAt( i ); • Objects we store in a vector can be accessed by giving their index position in the vector, much like the way we did with the array. • We need to type cast the element to a String, because the elements inside a vector can be an instance of any class. • A compile-time error will occur if we forget to type-cast the returned element. CS 1
Vectors Car myCar; int limit = carList.size( ); for (int k=0; k < limit; k++) { myCar = (Car) carList.elementAt( k ); System.out.println( myCar.maker()); } • Here is a code to display the name of all cars in the carList vector. • Vector elements are always objects. They cannot be primitive types. CS 1