24
Expandable Vector Expandable Vector Useful alternative to array, Useful especially when the size is uncertain

Expandable Vector

  • Upload
    thea

  • View
    58

  • Download
    0

Embed Size (px)

DESCRIPTION

Expandable Vector. Useful alternative to array, Useful especially when the size is uncertain. Difference from Array. Can store any number of elements into a vector Can store only class instances in a vector Provided in Java's util package - PowerPoint PPT Presentation

Citation preview

Page 1: Expandable Vector

Expandable VectorExpandable Vector

Useful alternative to array,

Useful especially when the size is uncertain

Page 2: Expandable Vector

Difference from ArrayDifference from Array

Can store any number of elements into a vector

Can store only class instances in a vector

Provided in Java's util packageMust include import java.util.* at the beginning of the file

Page 3: Expandable Vector

Declaring and Using a Vector VariableDeclaring and Using a Vector Variable

Just as you declare other class variablesVector v = new Vector();

Add an element(instance of a class) m to the backend of a vector v.addElement(m);

Add at a particular place: insertElementAt(m, index)v.insertElementAt(m, 0); //add to the front end, displacing others

Remove from a particular place: deleteElementAt(m, index)v.deleteElementAt(0); //remove the first element, displacing others

Read the element at the front end and the backend of a vectorv.firstElementAt() v.lastElement()

Page 4: Expandable Vector

Queue and Stack using VectorQueue and Stack using Vector

FIFO Queue

addElement(), firstElement(), deleteElementAt()

LIFO Stack

insertElement(), firstElement(), deleteElementAt()

Page 5: Expandable Vector

Retrieving and Replacing an ElementRetrieving and Replacing an Element

Retrieve an elementv.elementAt(index)

Replace an elementv.setElementAt(m, index)

The size of a vectorv.size()

Page 6: Expandable Vector

ObjectObject Argument and Return Type Argument and Return Type

public final Object elementAt(int index) { }public final void addElement(Object obj) { }

Suppose the vector stores Movie instances(v.firstElement()).rating() // rating() is not defined in Object

Typecasting ( (Movie) (v.firstElement())).rating() // rating() is not defined in Object

Page 7: Expandable Vector

ObjectObject Argument Type Argument Type

All vector elements must be class instances. Then, how to make a vector of integers? ☞ Use a wrapper class Integer

Integer i = new Integer(100);v.addElement(i);System.out.println("Value is " + i.intValue());System.out.println("Value is " + i);

String s = "120";System.out.println("Value is " + Integer.valueOf(s));

There are other wrapper classes: Double ,Float ,Long

Page 8: Expandable Vector

EnumerationEnumeration

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

System.out.println(((Movie) (v.firstElement())).rating());

}

Page 9: Expandable Vector

Movie ExampleMovie Example

import java.io.*; import java.util.*; public class Demonstrate {

public static void main(String argv[]) throws IOException {Vector mainVector = Auxiliaries.readData("input.data");int counter; int size = mainVector.size();for(counter = 0; counter < size; ++counter) {

System.out.println( ((Movie)mainVector.elementAt(counter)).rating()

);}

}}

Page 10: Expandable Vector

Movie Example ( cont’ )Movie Example ( cont’ )

import java.io.*; import java.util.*; public class Auxiliaries {

public static Vector readData(String fileName) throws IOException {FileInputStream inputFile = new FileInputStream(fileName);StreamTokenizer tokens = new StreamTokenizer(inputFile);Vector v = new Vector();while(tokens.nextToken()!= tokens.TT.EOF) {

int x = (int)tokens.nval;tokens.nextToken();int y = (int) tokens.nval;tokens.nextToken(); int z = (int) tokens.nval;v.addElement(new Movie(x, y, z));

}inputFile.close();return v;

}}

Page 11: Expandable Vector

StringString and and StringBufferStringBuffer Classes and Characters Classes and Characters

Strings are first-class citizens in Java, unlike in C or C++ where a string is a null-terminated array of characters.

String class is for constant strings while StringBuffer class is for strings that will be modified.

Page 12: Expandable Vector

Creation of StringsCreation of Strings

Creation of a string

Many strings are created from string literals

"I am a boy"String s = "I am a boy"

Creation of a string object using a new keyword

new String("I am a boy")String s = new String("I am a boy");

Page 13: Expandable Vector

Access Methods of StringAccess Methods of String

Strings of type String are constants

Can concatenate two strings (+) to produce a new, longer string Cannot add, delete, or change the characters in strings To determine the length of a string,

use string.length() To extract a particular character from a string,

use string.charAt(inde x) To extract a position of a particular character,

use indexOf(char) or lastIndexOf(char) To extract a substring of a string,

use substring()

Page 14: Expandable Vector

Access Methods of String ( cont’ )Access Methods of String ( cont’ )

String extension() {int dot = filename.lastIndexOf('.');return filename.substring(dot+1);

}

String path() {int sep = filename.lastIndexOf('/');return filename.substring(0,sep);

}

Page 15: Expandable Vector

StringBuffer ClassStringBuffer Class

If the characters of a string will change, use a StringByffer class

class ReverseString {public static String reverseIt (String src) {

int len = src.length();StringBuffer dest = new StringBuffer(len);for ( int i= (len-1); i >= 0; i--) {

dest.append(src.charAt(i));}return dest.toString();

}}

Page 16: Expandable Vector

Access Methods of StringBufferAccess Methods of StringBuffer

To append a character at the end of a StringBuffer, use append()

To insert data (substring) in the middle of a StringBuffer, use insert()

StringBuffer s = new StringBuffer("Drink Java");s.insert(6, "Hot ");

To replace a character at a specific location,use setCharAt()

Page 17: Expandable Vector

Converting Objects to StringsConverting Objects to Strings

It is necessary and convenient to convert an object into a string

All classes inherit toString method from the Object class and many classes in java.lang override it appropriately (e.g., all type wrapper classes override toString() for their string representation)

Converting Strings to Numbers:

String pi = "3.14159";Float pi = Float.valueof(pi);

Page 18: Expandable Vector

Example in the TextbookExample in the Textbook

import java.io.*; import java.util.*; public class Demonstrate {

public static void main(String argv[]) throws IOException {Vector mainVector; mainVector = Auxiliaries.readMixture("input.data");int counter; int size = mainVector.size();for (counter = 0; counter < size; ++counter) {

System.out.println(

((Attraction)mainVector.elementAt(counter )).rating());

}}

}

Page 19: Expandable Vector

Example in the Textbook ( cont’ )Example in the Textbook ( cont’ )

import java.io.*; import java.util.*; public class Auxiliaries {

public static Vector readMixture(String fileName) throws IOException {FileInputStream inputFile = new FileInputStream(fileName);StreamTokenizer tokens = new StreamTokenizer(inputFile);Vectore v = new Vector();while(tokens.nextToken()!= tokens.TT.EOF) {

String codeString = tokens.sval;tokens.nextToken(); int x = (int) tokens.nval;tokens.nextToken(); int y = (int) tokens.nval;tokens.nextToken(); int z = (int) tokens.nval;

Page 20: Expandable Vector

Example in the Textbook ( cont’ )Example in the Textbook ( cont’ )

switch(codeString.charAt(0)) {case M : v.addElement(new Movie(x, y, z)); break;case S : v.addElement(new Symphony(x, y, z));

break;}

}inputFile.close();return v;

}}

---------input.data---------M 4 7 3M 8 8 7S 10 9 3

Page 21: Expandable Vector

Advanced Features of TokenizerAdvanced Features of Tokenizer

Make a tokenizer to return a token for the end of a line token_variable.eolIsSignificant(true);

To know if the current token represents the end of a line token_variable.nextToken() == token_variable.TT_EOL

Make a tokenizer to use the double quotation mark to delimit strings with embedded spaces

token_variable.quoteChar(( in t) '"');

Character values can be used in switch statements Because char is an integral type

Page 22: Expandable Vector

Movie reading programMovie reading program

import java.io.*; import java.util.*; public class Demonstrate {

public static void main(String argv[]) throws IOException {Vector mainVector; mainVector = Auxiliaries.readMovieFile("input.data ");int counter; int size = mainVector.size();for(counter = 0; counter < size; ++counter) {

System.out.println( ((Movie)mainVector.elementAt(counter)).rating()

);}

}}

Page 23: Expandable Vector

Movie reading program ( cont’ )Movie reading program ( cont’ )

import java.io.*; import java.util.*; public class Auxiliaries {

public static Vector readMovieFile(String fileName) throws IOException {FileInputStream inputFile = new FileInputStream(fileName);StreamTokenizer tokens = new StreamTokenizer(inputFile);tokens.quoteChar((int) '"'); tokens.eolIsSignificant(true);Vector v = new Vector();

while(tokens.nextToken()!= tokens.TT.EOF) {String nameString = tokens.sval;tokens.nextToken(); int x = (int) tokens.nval;tokens.nextToken(); int y = (int) tokens.nval;tokens.nextToken(); int z = (int) tokens.nval;

Page 24: Expandable Vector

Movie reading program ( cont’ )Movie reading program ( cont’ )

Movid m = (new Movid(x,y, z));m.title = nameString;if (tokens.nextToken()== tokens.TT.EOL) { }else { m.poster= tokens.sval;

tokens.nextToken(); }v.addElement(m);

}inputFile.close();return v;

}}

----------input.data----------“ABC KK" 4 7 3 "http://www.holywood.com/~abc""DEF" 8 8 7