Lecture20 vector

23
Vector By By Norazah Yusof Software Engineering Department Software Engineering Department Faculty of Computer Science and Information Systems 1

description

OOP

Transcript of Lecture20 vector

Page 1: Lecture20 vector

Vector

ByBy

Norazah YusofSoftware Engineering DepartmentSoftware Engineering Department

Faculty of Computer Science and Information Systems

1

Page 2: Lecture20 vector

Vector

Size of an array is fixed for the duration of the execution program.V t i fl ibl d t t t hi h ll it i t b h dVector is a more flexible data structure which allows its size to be changed.

A vector class is part of the java.util packageIt d i ll h i k d dIt can dynamically shrink or grow as neededA data element can be inserted into or removed from any location of a vector with a single method invocation. The elements of a vector must be objects (cannot be primitive types - if you need to store a primitive type, you need to use appropriate wrapper classes).It provides several instance methods to manage the list of objectsA Vector is basically the same as an ArrayList, but Vector

2

methods are synchronized for thread safety.

Page 3: Lecture20 vector

From the Library: java.util.VectorFrom the Library: java.util.Vector

The java.util.Vector class implements an array of objects that can j p y jgrow as needed (dynamic).

the size of a vector does not have to be declared - it grows and shrinks as needed

R l li it d t th i i iti l i Th tRegular arrays are limited to their initial size. They cannot grow or shrink. (static)There are methods to add , retrieve, insert in the middle of the vector or remove elementsvector, or remove elements

3

Page 4: Lecture20 vector

Vectors ‐ API documentation (partial listing)

public class Vector extends Object implements Cloneable, Serializable{

// constructorspublic Vector (int initialCapacity);public Vector();

// Instance methods for different functions

Allows specification of initial capacity of vector

// Instance methods for different functionspublic final void addElement (Object obj); - insert element at next free locationpublic final int capacity(); - return capacity of vectorpublic final Object elementAt(int index);- return object stored at the position ‘index’

bli fi l Obj fi El () fi l ( bj i i 0)public final Object firstElement(); - return first element (object at vector position 0)public final int indexOf(Object elem); - return index of the given element in vectorpublic final Object lastElement(); - return last element (object at position size-1)public final synchronized boolean removeElement(Object obj); - removes specified objectpublic final synchronized boolean removeElement(Object obj); removes specified objectpublic final synchronized void removeAllelements(); - removes all objectspublic final int size(); - return number of objects stored in the vectorpublic final void trimToSize(); - reduce capacity of the vector to the number of elements

}

4

}

Page 5: Lecture20 vector

Example 1 of Vector: L b 6 E i 1 Q i 5Lab 6 Exercise 1, Question 5

Use vector to store a collection of data that contains texts (i.e. faculty names).Import statement:p

import java.util.*;Declare a Vector object of faculty:

V t f lt V t ()Vector faculty = new Vector();

A Vector of size 0 is created.

5

Page 6: Lecture20 vector

Example 1 of VectorExample 1 of Vector

Add new element to a data collection:Add new element to a data collection:faculty.addElement ("FSKSM");faculty.addElement ("FS");faculty.addElement ("FKE");faculty.addElement ("FAB");

Th V t ill t i th l t iThe Vector will contain three elements in location 0, 1, and 2.

Display the content of vector:p ySystem.out.println(faculty);

Display the size of the vector:System out println(faculty size());

6

System.out.println(faculty.size());

Page 7: Lecture20 vector

Example 1 of VectorExample 1 of Vector

To insert new element at the third element of the vector:faculty.insertElementAt ("FPPSM", 2);

"FPPSM" is stored in between "FS" and "FKE""FPPSM" is stored in between "FS", and "FKE".Display the content of vector:

System.out.println(faculty);Display the size of the vector:

System.out.println(faculty.size());

To remove element with content "FKE" in theTo remove element with content "FKE" in the vector:

faculty.removeElement ("FKE");

7

Page 8: Lecture20 vector

Example 1 of VectorExample 1 of Vector

To remo e element at the third element of the ector:To remove element at the third element of the vector:faculty.removeElementAt (1);

"FS" will be deleted.To display the content of vector at the specified element:

System out println (faculty elementAt(1));System.out.println (faculty.elementAt(1));

"FPPSM" will be displayed.To change the value of specific element of a

tvectorfaculty.setElementAt("FKSG",2);

The content of element three will be replaced by

8

p y"FKSG“.

Page 9: Lecture20 vector

Wrapper Classespp

• Boolean Integer NOTE: (1) The wrapper classes do

• Character

• Short

IntegerLong

Float

not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their i l l b h d• Byte Double internal values cannot be changed once the objects are created.

Object Comparable

Character Boolean Number

9

Double Float Long Integer Short Byte

Page 10: Lecture20 vector

The toString, equals, and hashCodeMethods

• Each wrapper class overrides the toString, equals, and hashCode methods defined in the Object class. 

• Since all the numeric wrapper classes and the• Since all the numeric wrapper classes and the Character class implement the Comparableinterface the compareTo method isinterface, the compareTo method is implemented in these classes. 

10

Page 11: Lecture20 vector

The Number Class

Each numeric wrapper class extends the abstractEach numeric wrapper class extends the abstract Number class, which contains the methods doubleValue, floatValue, intValue, longValue, shortValue, and byteValue. 

These methods “convert” objects into primitiveThese methods  convert  objects into primitive type values. The methods doubleValue, floatValue, intValue, longValue are abstract. The , , gmethods byteValue and shortValue are not abstract, which simply return (byte)intValue() and 

11

(short)intValue(), respectively. 

Page 12: Lecture20 vector

The Integer and Double Classes

java.lang.Integer

-value: int +MAX_VALUE: int +MIN VALUE: int

java.lang.Number +byteValue(): byte +shortValue(): short +MIN_VALUE: int

+Integer(value: int) +Integer(s: String) +valueOf(s: String): Integer

s o V ue(): s o+intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double

+valueOf(s: String, radix: int): Integer+parseInt(s: String): int +parseInt(s: String, radix: int): int

j l D bl

java.lang.Comparable +compareTo(o: Object): int java.lang.Double

-value: double +MAX_VALUE: double +MIN_VALUE: double

p ( j )

+Double(value: double) +Double(s: String) +valueOf(s: String): Double +valueOf(s: String, radix: int): Double + D bl ( St i ) d bl

12

+parseDouble(s: String): double+parseDouble (s: String, radix: int): double

Page 13: Lecture20 vector

The Integer Classand the Double Class

• Constructors

• Class Constants MAX_VALUE, MIN_VALUE

• Conversion Methods

13

Page 14: Lecture20 vector

Numeric Wrapper Class ConstructorsNumeric Wrapper Class Constructors

You can construct a wrapper object either from a primitive data type value or from a string representing the numeric value. The constructors for Integer and Double are:

public Integer(int value)

public Integer(String s)public Integer(String s)

public Double(double value)

14

public Double(String s)

Page 15: Lecture20 vector

Numeric Wrapper Class Constants

• Each numerical wrapper class has the constantsEach numerical wrapper class has the constants MAX_VALUE and MIN_VALUE. MAX_VALUE represents the maximum value of the corresponding primitive data type. 

• For Byte, Short, Integer, and Long, MIN_VALUE represents the minimum byte, short, int, and long values. For Float and Double MIN VALUE represents the minimum positive floatDouble, MIN_VALUE represents the minimum positive floatand double values. 

• The following statements display the maximum integerThe following statements display the maximum integer (2,147,483,647), the minimum positive float (1.4E‐45), and the maximum double floating‐point number (1 79769313486231570 +308d)

15

(1.79769313486231570e+308d). 

Page 16: Lecture20 vector

Conversion Methods

• Each numeric wrapper class implements the• Each numeric wrapper class implements the abstract methods doubleValue, floatValue, intValue longValue and shortValue whichintValue, longValue, and shortValue, which are defined in the Number class. 

• These methods “convert” objects into primitive type values. 

16

Page 17: Lecture20 vector

Wrapper Classes for primitive types

• Wrapper class: a class that stores a primitive type value in an object and contains methods for converting back and forth 

• All are defined in in the java.lang package of the Java API (Application Programming Interface ‐ a standard set of Java class libraries). 

Each wrapper class includes the following constructors and methods:Each wrapper class includes the following constructors and methods:• a constructor that takes a primitive type value and converts it into an

objectDouble w = new Double (3.14159);

• a constructor that takes a string representation of a primitive type• a constructor that takes a string representation of a primitive type value

Double w = new Double ( “3.14159” );• a toString() method that creates a string version of the object’s value

w toString() returns the string “3 14159”w.toString() returns the string 3.14159• a typeValue method (i.e., intValue , doubleValue ) that returns the

primitive type value stored in the wrapper object:w.doubleValue() returns the double value 3.14159

• an equals method that compare for equality to wrapper objects of the

17

• an equals method that compare for equality to wrapper objects of the same class: assuming that x and y are of type Double, thenx.equals(y) returns true when they wrap the same value.

Page 18: Lecture20 vector

Vector (cont.): Example 2

import java.util.Vector;

class Perisian_Komputer

{ public static void main(String[]arg)

{ Vector perisian = new Vector();{ Vector perisian = new Vector();

String nama = new String("Visual Image");

Integer siri = new Integer(1235);

Double harga = new Double(2134.5);

String pengeluar = new String("Oracle");

Character test = new Character('a');

Float code = new Float(12.34f);

perisian addElement(nama);

18

perisian.addElement(nama);

perisian.addElement(siri);

Page 19: Lecture20 vector

Vector (cont.): Example 2(cont.)

perisian.addElement(harga);perisian.addElement(harga);

perisian.addElement(pengeluar);

perisian.addElement(test);

perisian.addElement(code);

System.out.println("Kandungan vektor:");

System.out.println(perisian);

}

}

19

Page 20: Lecture20 vector

Wrapper Classes for primitive types, cont’d• Example of use: store in Vectors (where primitive types cannot be stored).cont’d.p ( p yp )

double x = 13.5;Vector numbers  = new Vector();numbers.addElement(new Double(x)); double y = ((Double) numbers.elementAt(0)).doubleValue();

Assume vector v contains a collection of objects, some of which are type Double. The statements below store some objects in vector v. The loop adds only the numbers wrapped in the type Double objects and displays their sum (50.5).Vector v = new Vector();v.addElement("Jamil"); // first element is a stringv.addElement(new Double(15.0)); // second element is type Doublev.addElement(new Double(35.5)); // third element is type Doublev.addElement(new Integer(100)); // fourth element is type Integer

double sum = 0.0;

for (int i = 0; i < v.size(); i++) {

stores newInteger object

in v.Object temp = v.elementAt(i);

if (temp instanceof Double)

sum + = ((Double) temp).doubleValue();

}

true if tempis type Double

20

}

System.out.println("Sum of elements in vector v is " + sum);

Page 21: Lecture20 vector

Vectors ExamplepUse the Vector class to store a collection of employee:– import stmt:   import java.util.*;

– data declaration: Vector employees = new Vector();

– add existing objects: employees.addElement(employeeA);l ddEl ( l B)employees.addElement(employeeB);

– access 2nd element:  anEmployee = (Employee) employees elementAt(1);

01

employeeA

employeeBanEmployee = (Employee) employees.elementAt(1);

– change an element:  employees.setElementAt(employeeA, 1);

p y

employeeA0employees.setElementAt(employeeA, 1);

– insert an element: employees.insertElementAt(employeeB, 1);employeeA

0

1

21

employeeB

01

2

Page 22: Lecture20 vector

Vectors example, cont’d.Vectors example, cont d.remove an element: employees.removeElementAt(0);

employeeB01

employeeA

22

Page 23: Lecture20 vector

Methods for Vector classMethod call Effect

Vector() Constructs an empty vector (type of elementsdoes not need to be specified)does not need to be specified)

Employees.addElement(Emp1) Appends object Emp1 to vector employees andincrements its size

(Employee)employees.elementAt(0) Returns the object at index 0 and converts it toE ltype Employee

Employees.size() Returns the size of vector employees

employees.setElementAt(Emp2, 1) Changes the object at index 1 to Emp2p y ( p , ) Changes the object at index 1 to Emp2

employees.insertElementAt(anEmp,1)

Insert object anEmp at index 1, shifting theelements that follow up one position. Increment

t ivector size.employees.removeElementAt(1) Remove the element at index 1, shifting the

elements that follow down one position.Decrement vector size.

23

employees.toString() Forms a string enclosed in square brackets. Theobjects in employees are separated by commas.