Download presentation
Presentation is loading. Please wait.
Published byAugustine Goodman Modified over 8 years ago
1
Seven Lecture Collection 1
2
2 Some Legacy Collection Types ArrayList Enumeration Vector HashTable – self study
3
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
4
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
5
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
6
Because they are constants, the names of an enum type's fields are in uppercase letters. 6
7
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } 7 Enumeration Example1
8
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.)
9
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.)
10
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)
11
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
12
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
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
14 Enumeration Types (continued)
15
15 Enumeration Types (continued)
16
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
17
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
18
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
19
Flowchart for switch statement Oops: If you forget a break, one case runs into the next! expression? statement value
20
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
21
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
22
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: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
23
Another Example 23 public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7), 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; }
24
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 = 6.67300E-11; public double surfaceGravity() { return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } }
25
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.)
26
The output 26 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Your weight on JUPITER is 442.847567 Your weight on SATURN is 186.552719 Your weight on URANUS is 158.397260 Your weight on NEPTUNE is 199.207413 Your weight on PLUTO is 11.703031
27
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
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
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
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
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
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 }
33
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.