Seven Lecture Collection 1. 2 Some Legacy Collection Types  ArrayList  Enumeration  Vector  HashTable – self study.

Slides:



Advertisements
Similar presentations
9-Jun-14 Enum s (and a review of switch statements)
Advertisements

Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 17.
More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Misc Language Features Features that were added relatively recently that are now in common use.
16-Jul-15 Java Versions of Java Java 1 Java 2 Java 5.0 Oak: Designed for embedded devices Java 1.1: Adds inner classes and a completely new event-handling.
ArrayList, Multidimensional Arrays
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
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.
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.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
11-Jan-16 Bits and Pieces Some random things in Java.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 Enums (Chapter 4) To enumerate is: to name things one after another in a list Java has a type, called an enum, where a programmer specifies a finite.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
New Java Features Advanced Programming Techniques.
SCJP 5, 1/7 Declarations, Initialization and Scoping
Lecture 5:Interfaces and Abstract Classes
Chapter VII: Arrays.
OOP Tirgul 12.
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Sixth Lecture ArrayList Abstract Class and Interface
Elementary Programming
Array, Strings and Vectors
Lecture 5: Some more Java!
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Some random things in Java
Enumerated DATA Types Enum Types Enumerated Data Types
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
Java Collections Overview
Chapter 9 Inheritance and Polymorphism
Some random things in Java
(and a review of switch statements)
(and a review of switch statements)
Some random things in Java
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
Arrays and Collections
Object Oriented Programming in java
Enumerated DATA Types Enum Types Enumerated Data Types
ArrayLists 22-Feb-19.
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Java Programming Language
Data Structures & Algorithms
Some random things in Java
ArrayLists 27-Apr-19.
CSE 143 Lecture 2 ArrayIntList, binary search
Creating and Modifying Text part 3
Java 5 New Features 1-May-19.
Review: libraries and packages
Chapter 11 Inheritance and Polymorphism Part 1
Chap 2. Identifiers, Keywords, and Types
Additional control structures
Software Design Lecture : 34.
Review for Midterm 3.
Arrays.
Interfaces, Enumerations, Boxing, and Unboxing
Presentation transcript:

Seven Lecture Collection 1

2 Some Legacy Collection Types  ArrayList  Enumeration  Vector  HashTable – self study

 In the past, enumerations were usually represented as integer values:  public final int SPRING = 0; public final int SUMMER = 1; public final int FALL = 2; public final int WINTER = 3;  This is a nuisance, and is error prone as well  season = season + 1;  now = WINTER; …; month = now;  Here’s the new way of doing it:  enum Season { WINTER, SPRING, SUMMER, FALL } Enumerations

 An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. 4 Enumeration

 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 5 Enumeration Types

 Because they are constants, the names of an enum type's fields are in uppercase letters. 6

 public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } 7 Enumeration Example1

public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; 8 Enumeration Example(cont.)

case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } 9 Enumeration Example(cont.)

 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 10 Enumeration Types (continued)

 An enum is actually a new type of class  You can declare them as inner classes or outer classes  You can declare variables of an enum type and get type safety and compile time checking  Each declared value is an instance of the enum class  Enums are implicitly public, static, and final  You can compare enums with either equals or == enum s are classes

 enum s extend java.lang.Enum and implement java.lang.Comparable  Hence, enums can be sorted  Enums override toString() and provide valueOf()  Example:  Season season = Season.WINTER;  System.out.println(season ); // prints WINTER  season = Season.valueOf("SPRING"); // sets season to Season.SPRING enum s are classes

13 Enumeration Types (continued)  Because each enum type is a class, it can contain  Constructors, ( private ) data members, and methods  enum type considerations  You cannot instantiate objects using the operator new  Constructors are implicitly private

14 Enumeration Types (continued)

15 Enumeration Types (continued)

 Example:  enum Season { WINTER, SPRING, SUMMER, FALL }  This constructs the four named objects, using the default constructor  Example 2:  public enum Coin { private final int value; Coin(int value) { this.value = value; } PENNY(1), NICKEL(5), DIME(10), QUARTER(25); }  Enum constructors are only available within the Enum itself  An enumeration is supposed to be complete and unchangeable Enums have weird constructors

 Enums provide compile-time type safety  int enums don't provide any type safety at all: season = 43;  Enums provide a proper name space for the enumerated type  With int enums you have to prefix the constants (for example, seasonWINTER or S_WINTER ) to get anything like a name space.  Enums are robust  If you add, remove, or reorder constants, you must recompile, and then everything is OK again  Enum printed values are informative  If you print an int enum you just see a number  Because enums are objects, you can put them in collections  Because enums are classes, you can add fields and methods Advantages of the new enum

Syntax of the switch statement  The syntax is: switch ( expression ) { case value1 : statements ; break ; case value2 : statements ; break ;...(more cases)... default : statements ; break ; }  The expression must yield an integer or a character  Each value must be a literal integer or character  Notice that colons ( : ) are used as well as semicolons  The last statement in every case should be a break;  I even like to do this in the last case  The default: case handles every value not otherwise handled  The default case is usually last, but doesn't have to be

Flowchart for switch statement Oops: If you forget a break, one case runs into the next! expression? statement value

switch (cardValue) { case 1: System.out.print("Ace"); break; case 11: System.out.print("Jack"); break; case 12: System.out.print("Queen"); break; case 13: System.out.print("King"); break; default: System.out.print(cardValue); break; } Example switch statement

 switch statements can now work with enums  The switch variable evaluates to some enum value  The values for each case must (as always) be constants  switch ( variable ) { case constant : …; }  In the switch constants, do not give the class name— that is, you must say case SUMMER:, not case Season.SUMMER:  It’s still a very good idea to include a default case Enums and the switch statement

Example enum and switch public void tellItLikeItIs(DayOfWeek day) { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } Source:

Another Example 23 public enum Planet { MERCURY (3.303e+23, e6), VENUS (4.869e+24, e6), EARTH (5.976e+24, e6), MARS (6.421e+23, e6), JUPITER (1.9e+27, e7), SATURN (5.688e+26, e7), URANUS (8.686e+25, e7), NEPTUNE (1.024e+26, e7), PLUTO (1.27e+22, 1.137e6); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }

Another Example(cont.) 24 public double mass() { return mass; } public double radius() { return radius; } // universal gravitational constant (m 3 kg -1 s -2 ) public static final double G = E-11; public double surfaceGravity() { return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } }

25 public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } Another Example(cont.)

The output 26 Your weight on MERCURY is Your weight on VENUS is Your weight on EARTH is Your weight on MARS is Your weight on JUPITER is Your weight on SATURN is Your weight on URANUS is Your weight on NEPTUNE is Your weight on PLUTO is

27 Vector Class  The Vector class implements a growable array of objects.  Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

28 Vector Class  In Java this is supported by Vector class contained in java.util package. The Vector class can be used to create generic dynamic arrays that hold objects of any type or any number. The objects do not have to be homogeneous.  Like arrays, Vectors are created as follows:  Vector list = new Vector(); // declaring without size  Vector list = new Vector(3); // declaring with size

29 Vector properties  Vectors posses a number of advantages over arrays:  It is convenient to use vectors to store objects.  A vector can be used to store list of objects that may vary in size.  We can add and delete objects from the list as an when required.  But vectors cannot be used to store basic data types (int, float, etc.); we can only store objects. To store basic data type items, we need convert them to objects using “wrapper classes”.

30 Important Methods in Vector class  addElement(Object item)  insertElementAt(Object item, int index)  elementAt(int index) – get element at index  removeElementAt(int index)  size()  clone() - Returns a clone of this vector.  clear() - Removes all of the elements from this Vector.  get(int index) - Returns the element at the specified position in this Vector. get  copyInto(array) – copy all items from vector to array.

31 Vector – Example 1 import java.util.*; public class VectorOne{ public static void main(String[] args) { Vector circleVector = new Vector(); System.out.println("Vector Length + “, circleVector.size()); // 0 for ( int i=0; i < 5; i++) { circleVector.addElement( new Circle(i) ); // radius of the Circles 0,1,2,3,4 } System.out.println("Vector Length = " + circleVector.size());// 5 }

32 Vector – Example 2 import java.util.*; public class VectorTwo{ public static void main(String[] args) { …… code from VectorOne goes here circleVector.insertElementAt( new Circle(20), 3); System.out.println(“Vector Length =“ + circleVector.size()); // 6 for ( int i = 0; i < 6; i++) { System.out.println("Radius of element [" + i + "] = " + ( (Circle) circleVector.elementAt(i)).getRadius()); // radius of the Circles are 0,1,2,20,3,4 }

Collection Advantages and Disadvantages 33 Advantages Can hold different types of objects. Resizable Disadvantages Must cast to correct type Cannot do compile-time type checking.