SlideShare una empresa de Scribd logo
1 de 23
Descargar para leer sin conexión
Vector

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



                                                      1
Vector

Size of an array is fixed for the duration of the execution program.
Vector is
V 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
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
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
Example 1 of Vector: 
Lab 6 Exercise 1, Question 5
L 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
Example 1 of Vector
  Example 1 of Vector
Add 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
Example 1 of Vector
   Example 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".
                                  "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 the
vector:
    faculty.removeElement ("FKE");


                                                            7
Example 1 of Vector
  Example 1 of Vector
To 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 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
vector
   t
faculty.setElementAt("FKSG",2);
   The content of element three will be replaced by
                                          p       y
   "FKSG“.

                                                        8
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
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
The Number Class

Each numeric wrapper class extends the abstract 
Each numeric wrapper class extends the abstract
Number class, which contains the methods 
doubleValue, floatValue, intValue, longValue, 
shortValue, and byteValue. 
These methods  convert objects into primitive
These methods “convert” objects into primitive 
type values. The methods doubleValue, 
floatValue, intValue, longValue are abstract. The 
           ,         ,   g
methods byteValue and shortValue are not 
abstract, which simply return (byte)intValue() and 
(short)intValue(), respectively. 
                                               11
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
The Integer Class
      and the Double Class
• Constructors

• Class Constants MAX_VALUE, MIN_VALUE

• Conversion Methods




                                         13
Numeric Wrapper Class Constructors
Numeric 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
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
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
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
Vector (cont.): Example 2


import 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
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
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 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 string
v.addElement(new Double(15.0)); // second element is type Double
v.addElement(new Double(35.5)); // third element is type Double
v.addElement(new Integer(100)); // fourth element is type Integer
                                                           stores new
double sum = 0.0;                                        Integer object
for (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
Vectors Example
                                   p
Use 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
Vectors example, cont d.
           Vectors example, cont’d.
remove an element:   employees.removeElementAt(0);


                                                     employeeB
                                           0
                                           1
                                                     employeeA




                                                                 22
Methods for Vector class
           Method call                                 Effect
Vector()                           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
                                        Employee
Employees.size()                   Returns the size of vector employees

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

employees.insertElementAt(anEmp, Insert object anEmp at index 1, shifting the
                            1)   elements that follow up one position. Increment
                                   vector size.
                                      t i
employees.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

Más contenido relacionado

La actualidad más candente

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi Kant Sahu
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

La actualidad más candente (20)

Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
 
Java String
Java String Java String
Java String
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Generics
GenericsGenerics
Generics
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on Python
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Cats in Scala
Cats in ScalaCats in Scala
Cats in Scala
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 

Destacado (11)

Computers
ComputersComputers
Computers
 
Computer Graphics
Computer GraphicsComputer Graphics
Computer Graphics
 
Vector Presentation
Vector PresentationVector Presentation
Vector Presentation
 
Classroom2
Classroom2Classroom2
Classroom2
 
Raster vs vector graphics
Raster vs vector graphicsRaster vs vector graphics
Raster vs vector graphics
 
Raster Vs. Vector Presentation1
Raster Vs. Vector Presentation1Raster Vs. Vector Presentation1
Raster Vs. Vector Presentation1
 
Vectors vs Rasters, Graphic Formats
Vectors vs Rasters, Graphic FormatsVectors vs Rasters, Graphic Formats
Vectors vs Rasters, Graphic Formats
 
Applications of computer
Applications of computerApplications of computer
Applications of computer
 
Windows series operating system
Windows series operating systemWindows series operating system
Windows series operating system
 
Vectors
Vectors Vectors
Vectors
 
Types and components of computer system
Types and components of computer systemTypes and components of computer system
Types and components of computer system
 

Similar a Lecture20 vector

Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
faithxdunce63732
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
rsnyder3601
 

Similar a Lecture20 vector (20)

Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manual
 
Struktur data 1
Struktur data 1Struktur data 1
Struktur data 1
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
 
Collections
CollectionsCollections
Collections
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
 
Java unit i
Java unit iJava unit i
Java unit i
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Último (20)

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Lecture20 vector

  • 1. Vector By Norazah Yusof Software Engineering Department Faculty of Computer Science and Information Systems 1
  • 2. Vector Size of an array is fixed for the duration of the execution program. Vector is V 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. 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. 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. Example 1 of Vector:  Lab 6 Exercise 1, Question 5 L 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. Example 1 of Vector Example 1 of Vector Add 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. Example 1 of Vector Example 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". "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 the vector: faculty.removeElement ("FKE"); 7
  • 8. Example 1 of Vector Example 1 of Vector To 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 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 vector t faculty.setElementAt("FKSG",2); The content of element three will be replaced by p y "FKSG“. 8
  • 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. 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. The Number Class Each numeric wrapper class extends the abstract  Each numeric wrapper class extends the abstract Number class, which contains the methods  doubleValue, floatValue, intValue, longValue,  shortValue, and byteValue.  These methods  convert objects into primitive These methods “convert” objects into primitive  type values. The methods doubleValue,  floatValue, intValue, longValue are abstract. The  , , g methods byteValue and shortValue are not  abstract, which simply return (byte)intValue() and  (short)intValue(), respectively.  11
  • 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. The Integer Class and the Double Class • Constructors • Class Constants MAX_VALUE, MIN_VALUE • Conversion Methods 13
  • 14. Numeric Wrapper Class Constructors Numeric 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. 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. 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. 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. Vector (cont.): Example 2 import 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
  • 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 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 string v.addElement(new Double(15.0)); // second element is type Double v.addElement(new Double(35.5)); // third element is type Double v.addElement(new Integer(100)); // fourth element is type Integer stores new double sum = 0.0; Integer object for (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. Vectors Example p Use 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. Vectors example, cont d. Vectors example, cont’d. remove an element: employees.removeElementAt(0); employeeB 0 1 employeeA 22
  • 23. Methods for Vector class Method call Effect Vector() 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 Employee Employees.size() Returns the size of vector employees employees.setElementAt(Emp2, 1) p y ( p , ) Changes the object at index 1 to Emp2 employees.insertElementAt(anEmp, Insert object anEmp at index 1, shifting the 1) elements that follow up one position. Increment vector size. t i employees.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