Lecture20 vector


Published on


Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Lecture20 vector

  1. 1. Vector By Norazah Yusof Software Engineering DepartmentFaculty of Computer Science and Information Systems 1
  2. 2. VectorSize of an array is fixed for the duration of the execution program.Vector isV t i a more fl ibl d t structure which allows its size to be changed. flexible data t t hi h ll it i t b h d A vector class is part of the java.util package It can d dynamically shrink or grow as needed i ll h i k d d A 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 objects A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety. 2
  3. 3. From the Library: From the Library: java.util.Vector The java.util.Vector class implements an array of objects that can j p y j grow as needed (dynamic). the size of a vector does not have to be declared - it grows and shrinks as needed Regular R l arrays are limited to their initial size. Th cannot grow or li it d t th i i iti l i They t shrink. (static) There are methods to add , retrieve, insert in the middle of the vector, vector or remove elements 3
  4. 4. Vectors ‐ API documentation (partial listing)public class Vector extends Object implements Cloneable, Serializable{ // constructors public Vector (int initialCapacity); public Vector(); Allows specification of initial capacity of vector // Instance methods for different functions public final void addElement (Object obj); - insert element at next free location public final int capacity(); - return capacity of vector public final Object elementAt(int index);- return object stored at the position ‘index’ public final Object firstElement(); - return fi element (object at vector position 0) bli fi l Obj fi El () first l ( bj ii public final int indexOf(Object elem); - return index of the given element in vector public final Object lastElement(); - return last element (object at position size-1) public final synchronized boolean removeElement(Object obj); - removes specified object public final synchronized void removeAllelements(); - removes all objects public final int size(); - return number of objects stored in the vector public final void trimToSize(); - reduce capacity of the vector to the number of elements} 4
  5. 5. Example 1 of Vector: Lab 6 Exercise 1, Question 5L b6E i 1 Q i 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: Vector f V t faculty = new V t () lt Vector(); A Vector of size 0 is created. 5
  6. 6. Example 1 of Vector Example 1 of VectorAdd new element to a data collection: faculty.addElement ("FSKSM"); faculty.addElement ("FS"); faculty.addElement ("FKE"); faculty.addElement ("FAB"); The Vector ill Th V t will contain three elements in t i th l t i location 0, 1, and 2.Display the content of vector: p y System.out.println(faculty);Display the size of the vector: System.out.println(faculty.size()); System out println(faculty size()); 6
  7. 7. Example 1 of Vector Example 1 of VectorTo insert new element at the third element of the vector: faculty.insertElementAt ("FPPSM", 2); "FPPSM" is stored in between "FS" and "FKE". "FS",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 thevector: faculty.removeElement ("FKE"); 7
  8. 8. Example 1 of Vector Example 1 of VectorTo remove element at the third element of the vector: remo e ector: faculty.removeElementAt (1); "FS" will be deleted. To display the content of vector at the specifiedelement: System.out.println (faculty.elementAt(1)); System out println (faculty elementAt(1)); "FPPSM" will be displayed.To change the value of specific element of avector tfaculty.setElementAt("FKSG",2); The content of element three will be replaced by p y "FKSG“. 8
  9. 9. Wrapper Classes pp• Boolean Integer NOTE: (1) The wrapper classes do not have no-arg constructors. (2)• Character Long The instances of all wrapper• Short Float classes are immutable, i.e., their internal values cannot be changed i l l b h d• Byte Double once the objects are created. Comparable Object Number Character Boolean Double Float Long Integer Short Byte 9
  10. 10. The toString, equals, and hashCode Methods• 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 Comparable interface, the compareTo method is  interface the compareTo method is implemented in these classes.  10
  11. 11. The Number ClassEach numeric wrapper class extends the abstract Each numeric wrapper class extends the abstractNumber 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 (short)intValue(), respectively.  11
  12. 12. The Integer and Double Classes java.lang.Number java.lang.Integer -value: int +byteValue(): byte +MAX_VALUE: int +shortValue(): s o s o V ue(): short +MIN_VALUE: +MIN VALUE: int +intValue(): int +longVlaue(): long +Integer(value: int) +floatValue(): float +Integer(s: String) +doubleValue():double +valueOf(s: String): Integer +valueOf(s: String, radix: int): Integer +parseInt(s: String): int java.lang.Comparable +parseInt(s: String, radix: int): int +compareTo(o: Object): int p ( j ) java.lang.Double j l D bl -value: double +MAX_VALUE: double +MIN_VALUE: double +Double(value: double) +Double(s: String) +valueOf(s: String): Double +valueOf(s: String, radix: int): Double +parseDouble(s: St i ) double + D bl ( String): d bl +parseDouble (s: String, radix: int): double 12
  13. 13. The Integer Class and the Double Class• Constructors• Class Constants MAX_VALUE, MIN_VALUE• Conversion Methods 13
  14. 14. 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) public Double(String s) 14
  15. 15. Numeric Wrapper Class Constants • Each numerical wrapper class has the constants  Each 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 Double MIN VALUE represents the minimum positive float and double values.  • The following statements display the maximum integer  The 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.79769313486231570e+308d).  (1 79769313486231570 +308d) 15
  16. 16. Conversion Methods• Each numeric wrapper class implements the Each numeric wrapper class implements the  abstract methods doubleValue, floatValue,  intValue, longValue, and shortValue, which  intValue longValue and shortValue which are defined in the Number class. • These methods “convert” objects into  primitive type values.  16
  17. 17. 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: • a constructor that takes a primitive type value and converts it into an object Double w = new Double (3.14159); • 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() w toString() returns the string “3 14159” 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 same class: assuming that x and y are of type Double, then x.equals(y) returns true when they wrap the same value. 17
  18. 18. Vector (cont.): Example 2import java.util.Vector;class Perisian_Komputer{ public static void main(String[]arg) { 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); perisian addElement(nama); perisian.addElement(siri); 18
  19. 19. Vector (cont.): Example 2(cont.)perisian.addElement(harga);perisian.addElement(pengeluar);perisian.addElement(test);perisian.addElement(code);System.out.println("Kandungan vektor:");System.out.println(perisian);}} 19
  20. 20. Wrapper Classes for primitive types, • cont’d. cont’d Example of use: store in Vectors (where primitive types cannot be stored). p double x = 13.5; ( p Vector numbers  = new Vector(); yp ) 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 statementsbelow store some objects in vector v. The loop adds only the numbers wrapped in the type Doubleobjects 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 stores newdouble sum = 0.0; Integer objectfor (int i = 0; i < v.size(); i++) { in v. Object temp = v.elementAt(i); true if temp if (temp instanceof Double) is type Double sum + = ((Double) temp).doubleValue();}System.out.println("Sum of elements in vector v is " + sum); 20
  21. 21. Vectors Example pUse 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); employees.addElement(employeeB); l ddEl ( l B) employeeA 0 – access 2nd element:   1 employeeB p y anEmployee = (Employee) employees.elementAt(1); anEmployee = (Employee) employees elementAt(1); – change an element:   employeeA 0 employees.setElementAt(employeeA, 1); employees.setElementAt(employeeA, 1); 1 employeeA – insert an element: employees.insertElementAt(employeeB, 1); 0 1 2 employeeB 21
  22. 22. Vectors example, cont d. Vectors example, cont’d.remove an element: employees.removeElementAt(0); employeeB 0 1 employeeA 22
  23. 23. Methods for Vector class Method call EffectVector() Constructs an empty vector (type of elements does not need to be specified)Employees.addElement(Emp1) Appends object Emp1 to vector employees and increments its size(Employee)employees.elementAt(0) Returns the object at index 0 and converts it to type E l EmployeeEmployees.size() Returns the size of vector employeesemployees.setElementAt(Emp2, 1) p y ( p , ) Changes the object at index 1 to Emp2employees.insertElementAt(anEmp, Insert object anEmp at index 1, shifting the 1) elements that follow up one position. Increment vector size. t iemployees.removeElementAt(1) Remove the element at index 1, shifting the elements that follow down one position. Decrement vector size.employees.toString() Forms a string enclosed in square brackets. The objects in employees are separated by commas. 23