Lecture20 vector

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

Embed Size (px)

description

OOP

Transcript of Lecture20 vector

  • 1. Vector ByNorazah YusofSoftware Engineering DepartmentFaculty of Computer Science and Information Systems1

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 dA vector class is part of the java.util packageIt can d dynamically shrink or grow as neededi ll h i kd dA data element can be inserted into or removed from anylocation of a vector with a single method invocation.The elements of a vector must be objects (cannot be primitivetypes - if you need to store a primitive type, you need to useappropriate wrapper classes).It provides several instance methods to manage the list ofobjectsA Vector is basically the same as an ArrayList, but Vectormethods are synchronized for thread safety. 2 3. FromtheLibrary:From the Library: java.util.Vector The java.util.Vector class implements an array of objects that can jp yj grow as needed (dynamic).the size of a vector does not have to be declared - itgrows 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 Theyt shrink. (static) There are methods to add , retrieve, insert in the middle of the vector, vector or remove elements3 4. Vectors APIdocumentation(partiallisting)public class Vector extends Object implements Cloneable, Serializable{// constructorspublic Vector (int initialCapacity);public Vector();Allows specification ofinitial 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 indexpublic final Object firstElement(); - return fi element (object at vector position 0)bli fi l Obj fi El ()first l( bjiipublic 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 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 5. Example1ofVector:Lab6Exercise1,Question5L b6Ei 1 Q i 5Use vector to store a collection of data that containstexts (i.e. faculty names).Import statement: p import java.util.*;Declare a Vector object of faculty:Vector fV tfaculty = new V t () ltVector(); A Vector of size 0 is created. 5 6. Example1ofVectorExample 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 lt i 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());System out println(faculty size()); 6 7. Example1ofVector 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. Example1ofVectorExample 1 of VectorTo remove element at the third element of the vector: remo eector: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 byp y "FKSG.8 9. WrapperClasses pp Boolean IntegerNOTE: (1) The wrapper classes do not have no-arg constructors. (2) Character Long The instances of all wrapper Short Floatclasses are immutable, i.e., their internal values cannot be changed il l b h d ByteDouble once the objects are created. Comparable Object NumberCharacter BooleanDoubleFloat LongInteger ShortByte 9 10. ThetoString,equals,andhashCodeMethods EachwrapperclassoverridesthetoString,equals,andhashCode methodsdefinedintheObject class. Since all the numeric wrapper classes and theSinceallthenumericwrapperclassesandtheCharacter classimplementtheComparableinterface,thecompareTo methodisinterface the compareTo method isimplementedintheseclasses. 10 11. TheNumber ClassEachnumericwrapperclassextendstheabstractEach numeric wrapper class extends the abstractNumber class,whichcontainsthemethodsdoubleValue,floatValue,intValue,longValue,shortValue,andbyteValue.Thesemethods convert objects into primitiveThese methods convertobjectsintoprimitivetypevalues.ThemethodsdoubleValue,floatValue,intValue,longValue areabstract.The , , gmethodsbyteValue andshortValue arenotabstract,whichsimplyreturn(byte)intValue() and(short)intValue(),respectively. 11 12. TheInteger andDouble Classesjava.lang.Number java.lang.Integer-value: int +byteValue(): byte +MAX_VALUE: int +shortValue(): s os 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): intjava.lang.Comparable+parseInt(s: String, radix: int): int +compareTo(o: Object): int p ( j ) java.lang.Double jlD 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. TheInteger ClassandtheDouble Class Constructors ClassConstantsMAX_VALUE,MIN_VALUE ConversionMethods 13 14. NumericWrapperClassConstructorsNumeric Wrapper Class ConstructorsYoucanconstructawrapperobjecteitherfromaprimitivedatatypevalueorfromastringrepresentingthenumericvalue.TheconstructorsforIntegerandDoubleare:publicInteger(intvalue)publicInteger(Strings)public Integer(String s)publicDouble(doublevalue)publicDouble(Strings)14 15. NumericWrapperClassConstants Eachnumericalwrapperclasshastheconstants Each numerical wrapper class has the constants MAX_VALUE andMIN_VALUE.MAX_VALUE representsthe maximumvalueofthecorrespondingprimitivedatatype. ForByte,Short,Integer,andLong,MIN_VALUE represents theminimumbyte,short,int,andlong values.ForFloat and Double,MIN_VALUE representstheminimumpositive Double MIN VALUE represents the minimum positive float anddouble values. Thefollowingstatementsdisplaythemaximuminteger The following statements display the maximum integer (2,147,483,647),theminimumpositivefloat(1.4E45),and themaximumdoublefloatingpointnumber (1.79769313486231570e+308d). (1 79769313486231570 +308d)15 16. ConversionMethods Each numeric wrapper class implements theEachnumericwrapperclassimplementstheabstractmethodsdoubleValue,floatValue,intValue,longValue,andshortValue,whichintValue longValue and shortValue whicharedefinedintheNumber class. Thesemethodsconvertobjectsintoprimitivetypevalues. 16 17. WrapperClassesforprimitivetypes Wrapperclass: aclassthatstoresaprimitivetypevalueinanobjectandcontainsmethodsforconvertingbackandforth Allaredefinedininthe java.lang packageoftheJavaAPI(ApplicationProgrammingInterface astandardsetofJavaclasslibraries).Each wrapper class includes the following constructors and methods: a constructor that takes a primitive type value and converts it into anobjectDouble w = new Double (3.14159); a constructor that takes a string representation of a primitive typevalueDouble w = new Double ( 3.14159 ); a toString() method that creates a string version of the objects valuew.toString()w toString() returns the string 3 141593.14159 a typeValue method (i.e., intValue , doubleValue ) that returns theprimitive 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 thesame class: assuming that x and y are of type Double, thenx.equals(y) returns true when they wrap the same value.17 18. Vector(cont.):Example2import 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. Vector(cont.):Example2(cont.)perisian.addElement(harga);perisian.addElement(pengeluar);perisian.addElement(test);perisian.addElement(code);System.out.println("Kandungan vektor:");System.out.println(perisian);}}19 20. WrapperClassesforprimitivetypes, contd. contdExampleofuse: storeinVectors(whereprimitivetypescannotbestored).pdouble x =13.5; (pVectornumbers=newVector(); yp )numbers.addElement(new Double(x));doubley=((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 tempif (temp instanceof Double) is type Doublesum + = ((Double) temp).doubleValue();}System.out.println("Sum of elements in vector v is " + sum);20 21. VectorsExample pUsetheVector classtostoreacollectionofemployee: importstmt: import java.util.*; datadeclaration: Vectoremployees=newVector(); addexistingobjects:employees.addElement(employeeA); employees.addElement(employeeB); l ddEl(l B) employeeA0 access2nd element:1 employeeB p y anEmployee=(Employee)employees.elementAt(1); anEmployee = (Employee) employees elementAt(1); changeanelement: employeeA0employees.setElementAt(employeeA,1);employees.setElementAt(employeeA, 1); 1employeeA insertanelement: employees.insertElementAt(employeeB,1);012 employeeB 21 22. Vectorsexample,cont d. Vectors example, contd.remove an element: employees.removeElementAt(0); employeeB 0 1 employeeA 22 23. MethodsforVectorclass 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 lEmployeeEmployees.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 the1) 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