Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Generics and the ArrayList Class
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Programming with Collections Collections in Java Using Arrays Week 9.
Fall 2007CS 2251 Enum Types from Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Arrays. Example Write a program to keep track of all students’ scores on exam 1. Need a list of everyone’s score Declare 14 double variables? What about.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Alice in Action with Java
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java Programming: Program Design Including Data Structures 1 Vectors The class Vector can be used to implement a list Unlike an array, the size of a Vector.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1,
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Recitation 5 Enums and The Java Collections classes/interfaces 1.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Chapter 10: Class Vector and String, and Enumeration Types Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Java Programming: Guided Learning with Early Objects Chapter 8 Applications of Arrays (Sorting and Searching) and Strings.
Seven Lecture Collection 1. 2 Some Legacy Collection Types  ArrayList  Enumeration  Vector  HashTable – self study.
CMSC 202 ArrayList Aug 9, 2007.
Chapter VII: Arrays.
Sixth Lecture ArrayList Abstract Class and Interface
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
ArrayLists.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
Arrays and Collections
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Arrays and Array Lists CS 21a.
Java Programming Language
slides created by Alyssa Harding
Presentation transcript:

Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types

A Weakness of Arrays  Suppose we declare an array of “Student” objects: Student[] students = new Student[10];  What if a new student joins the class?  The size of an array cannot be increased after it is instantiated Java Programming: Program Design Including Data Structures2

Resizing an Array (the hard way) Student[] students = new Student[10]; // do some stuff… // now we need to add student 11 Student[] students2 = new Student[11]; for(int i = 0; i < students.length; i++) { students2[i] = students[i]; } student[10] = new Student(); Java Programming: Program Design Including Data Structures3

4 class Vector  The class Vector can be used to implement a list, replacing a simple array  The size of a Vector object can grow/shrink during program execution  The Vector will automatically grow to accommodate the number of elements you put in it

Java Programming: Program Design Including Data Structures5 class Vector (continued)  The class Vector is contained in the package java.util  Programs must include either:  import java.util.*;  import java.util.Vector;

Vector Declaration  Declare/initialize Vector students = new Vector ();  The syntax is used to declare the type of object that will be stored in the Vector  If you add a different type of object, an exception is thrown  Not strictly necessary, but highly recommended (compiler warning) Java Programming: Program Design Including Data Structures6

Vector Size/Capacity  The size of a vector is the number of elements  The capacity of a vector is the maximum number of elements before more memory is needed  If size exceeds capacity when adding an element, the capacity is automatically increased  Declares a larger storage array  Copies existing elements, if necessary  Growing the capacity is expensive!  By default, the capacity doubles each time Java Programming: Program Design Including Data Structures7

Setting Initial Capacity  If you know you will need a large vector, it may be faster to set the initial capacity to something large Vector students = new Vector (1000); Java Programming: Program Design Including Data Structures8

Size and capacity  Get the current size and capacity: Vector students = new Vector (1000); students.size(); // returns 0 students.capacity(); // returns 1000  Setting size and capacity: // adds null elements or deletes elements if necessary students.setSize(10); // increases capacity if necessary students.ensureCapacity(10000); Java Programming: Program Design Including Data Structures9

10 Vector stringList = new Vector (); stringList.add("Spring"); stringList.add("Summer"); stringList.addElement("Fall"); stringList.addElement("Winter"); Adding Elements add and addElement have identical functionality

Java Programming: Program Design Including Data Structures11 stringList.get(0); // “Spring” stringList.get(3); // “Winter” stringList.get(4); // ArrayIndexOutOfBounds Exception Accessing Elements

Java Programming: Program Design Including Data Structures12 Primitive Data Types and the class Vector  Every component of a Vector object is a reference  Primitive data types are not objects  Corresponding to each primitive data type, Java provides a wrapper class  JDK 5.0 provides autoboxing and auto-unboxing of primitive data types

Java Programming: Program Design Including Data Structures13 Primitive Data Types and the class Vector (continued)  Creating a Vector of Integer objects Vector list = new Vector (); list.add(13); // with autoboxing list.add(new Integer(25)); // without autoboxing int tmp = list.get(0); // with autounboxing int tmp2 = list.get(0).intValue() //without

Java Programming: Program Design Including Data Structures14 Vector and the foreach loop  Each Vector object is a collection of elements  You can use a foreach loop to process its elements  Exactly like using a foreach loop with an array  Syntax: for (type identifier : vectorObject) statements

Java Programming: Program Design Including Data Structures15 Members of the class Vector

Java Programming: Program Design Including Data Structures16 Members of the class Vector (continued)

Java Programming: Program Design Including Data Structures17 Members of the class Vector (continued)

Java Programming: Program Design Including Data Structures18 Members of the class Vector (continued)

Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types (continued)

Exercise Java Programming: Program Design Including Data Structures20 Vector a = new Vector (); a.add(4); a.add(7); a.add(10); a.set(1, 5); int tmp = a.remove(0); System.out.println(tmp); System.out.println(a.indexOf(new Integer(10)); System.out.println(a.toString()); a.clear(); System.out.println(a.isEmpty());

Multi-dimensional Vectors  Can we have a 2d vector? Yes!  Just like a 2d array, but notation is more cumbersome Java Programming: Program Design Including Data Structures21

Multi-dimensional Vectors Java Programming: Program Design Including Data Structures22 Vector > a = new Vector >(); for (int i = 0; i < 4; i++) { Vector tmp = new Vector (); for (int j = 0; j < 4; j++) { tmp.add(i+j); } a.add(tmp); } System.out.println(a.get(2).get(3)); System.out.println(a.get(0).get(2));

Vector vs. ArrayList  Java has another class called ArrayList  This class is almost identical in function to Vector, and has most of the same methods  ArrayList is typically faster  ArrayList should *not* be used if your code is multi-threaded (i.e., if you allow parallel execution) Java Programming: Program Design Including Data Structures23

Java Programming: Program Design Including Data Structures24 Enumeration Types  Enumeration or enum types  User-defined data types  User specifies the values of that data type  Defined using the key word enum  Syntax example:  enum Grades {A, B, C, D, F};  The values are identifiers  Called enumeration or enum constants  Must be unique within an enum type

Java Programming: Program Design Including Data Structures25 Enumeration Types (continued)  Each enum type is a special type of class  Values are (special types of) objects of that class  Using an enum type Grades myGrade; myGrade = Grades.B; System.out.println (“myGrade: ” + myGrade);  Each enum constant has an ordinal value  Ordinal value of the first enum constant is 0

Java Programming: Program Design Including Data Structures26 Enumeration Types (continued)

Java Programming: Program Design Including Data Structures27 Enumeration Types (continued)  Because each enum type is a class, it can contain  Constructors, ( private ) data members, and methods  enum type considerations  Defined using enum rather than class  enum types are implicitly final  enum constants are implicitly static  You cannot instantiate objects using the operator new  Constructors are implicitly private  You cannot create new classes from an enum type

Java Programming: Program Design Including Data Structures28 Enumeration Types (continued)

Java Programming: Program Design Including Data Structures29 public enum Directions{North, South, East, West}; public int xPos = 0; public int yPos = 0; public void move(Directions dir) { switch(dir) { case Directions.North: yPos++; break; case Directions.South: yPos--; break; case Directions.East: xPos++; break; case Directions.West: xPos--; break; case default: System.out.println(“Invalid direction!”); }

Enumeration Types  See this site for more discussion and examples: anguage/enums.html anguage/enums.html Java Programming: Program Design Including Data Structures30

Strings  Strings are essentially arrays of characters  The string class provides many functions for manipulating strings  Searching/matching operations  Replacing characters  Finding characters  Trimming whitespace  Etc. Java Programming: Program Design Including Data Structures31

Java Programming: Program Design Including Data Structures32 class String (Revisited)

Java Programming: Program Design Including Data Structures33 class String (Revisited) (continued)

Java Programming: Program Design Including Data Structures34 class String (Revisited) (continued)

Java Programming: Program Design Including Data Structures35 class String (Revisited) (continued)