Vector Class A Vector is a class, which groups together objects of different data types.

Each vector maintains a capacity and capacityIncrement. As elements are added to a vector, storage for the vector increases, in chunks to the size of the capacityIncrement variable. The capacity of a vector is always atleast as large as the size of the vector.

The Vector class was introduced because the following were the limitations of arrays:a) b) c) The size cannot be dynamically changed . The elements in the array cannot interchange their positions. The array can contain only data types of similar type.

Vector Constructors Vector () –Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. Vector (int initialCapacity) – Constructs a empty vector with the specified storage capacity. Vector (int initialCapacity, int capacityIncrement) – Constructs a empty vector with the specified storage capacity and the specified increment.

For E.g. Vector (10,5) – Will construct a Vector with a initial capacity of 10 and a increment capacity of 5 elements and when the 11th element is added the capacity would increase to 15 directly and so on. Vector Methods The access methods provided by the Vector class support array-like operations and operations related to the size of Vector objects. The array-like operations allow elements to be added, deleted, and inserted into vectors. They also allow tests to be performed on the contents of vectors and specific elements to be retrieved.

-

The size-related operations allow the byte size and number of elements of the vector to be determined and the vector size to be increased to a certain capacity or trimmed to the minimum capacity needed.

Code import java.util.*; class Test89 { public static void main(String args[]) { // Create a vector and its elements Vector v = new Vector(); v.addElement(new Integer(5)); v.addElement(new Float(-14.14f)); v.addElement(new String("Hello")); v.addElement(new Long(120000000)); v.addElement(new Double(-23.45e-11)); // Display the vector elements System.out.println(v); // Insert an element into the vector String s = new String("String to be inserted"); v.insertElementAt(s, 1); System.out.println(v); // Remove an element from the vector v.removeElementAt(3); System.out.println(v); // Elements in a Vector System.out.println(v.size()); } } Output [5, -14.14, Hello, 120000000, -2.345E-10] [5, String to be inserted, -14.14, Hello, 120000000, -2.345E-10]

[5, String to be inserted, -14.14, 120000000, -2.345E-10] 5 IMP: The toString method has been overridden to print out the elements of the Vector separated by commas. Incase we want to capture the element at a position and capture that elements, we should use the method remove(int index) and this would return an object and it is the duty of the programmer to properly cast it to the respective data type. Code import java.util.*; class Test90 { public static void main(String args[]) { Vector v = new Vector(10,5); v.addElement(new Integer(5)); v.addElement(new Float(-14.14f)); v.addElement(new String("Hello")); v.addElement(new Long(120000000)); v.addElement(new Double(-23.45e-11)); System.out.println(v); Integer i = (Integer) v.remove(0); Float f = (Float)v.remove(0); System.out.println(i); System.out.println(f);

} } Output [5, -14.14, Hello, 120000000, -2.345E-10] 5 -14.14

Note: When we are removing the second element, we are again giving the position of 0 (zero) this is because once the first element is removed, all the elements would be going up by one. Code import java.util.Vector; class Test91 { String ename; Integer sal; public static void main(String as[]) { Vector v = new Vector(2,0); Test91 v1 = new Test91(); v1.ename = "raman"; v1.sal = new Integer(8000); Test91 v2 = new Test91(); v2.ename = "gopal"; v2.sal = new Integer(18000); v.addElement(v1.ename); v.addElement(v1.sal); v.addElement(v2.ename); v.addElement(v2.sal); System.out.println(v.capacity()); System.out.println(v.elementAt(0)); System.out.println(v.elementAt(1)); System.out.println(v.elementAt(2)); System.out.println(v.elementAt(3)); v.removeElementAt(1); System.out.println(v.elementAt(0)); System.out.println(v.elementAt(1)); System.out.println(v.elementAt(2)); // System.out.println(v.elementAt(3)); // System.out.println(v.indexOf("Gopal")); v.setElementAt("Gopal",1);

System.out.println(v.elementAt(1)); } } Output 4 raman 8000 gopal 18000 raman gopal 18000 Gopal

Enumeration Interface The Enumeration Interface facilitates a standard mechanism to retrieve elements across the different data structures in the util package. The Enumeration Interface defines the method by which you can enumerate (obtain one at a time) the elements in a collection of objects. hasMoreElements() Tests if this enumeration contains more elements.

boolean

Object nextElement() Returns the next element of this enumeration if this enumeration object has at least one more element to provide. Code import java.util.Vector; import java.util.Enumeration; public class Test92 { public static void main(String args[]) { Vector v = new Vector(); v.addElement("one"); v.addElement("two"); v.addElement("three"); v.insertElementAt("zero",0); v.insertElementAt("oops",3); v.insertElementAt("four",5); System.out.println("Size: "+v.size()); Enumeration enum = v.elements(); while (enum.hasMoreElements()) { System.out.print(enum.nextElement()+" "); } System.out.println(); v.removeElement("oops"); System.out.println("Size: "+v.size());

for(int i=0;i<v.size();++i) { System.out.print(v.elementAt(i)+" "); } System.out.println(); } } Output Size: 6 zero one two oops three four Size: 5 zero one two three four

Math class All the methods of this class, which performs basic numeric operations, are static.

The Important Methods of this class are: 1) static double ceil (double a) – This method returns the next whole number up that is an integer (This is for +ve numbers and for negative numbers it is the opposite). static double floor (double a) – This method returns the next whole number down that is an integer. (This is for +ve numbers and for negative numbers it is the opposite). static double random() – This generates a number between 0.0 but less than 1.0 static double sqrt (double a) – This returns the square root of the double parameter.

2)

3) 4) Code

class MathExample { public static void main(String args[]) { int i = 7; int j = -9; double x = 72.3; double y = 0.34; System.out.println("i is " + i); System.out.println("j is " + j); System.out.println("x is " + x); System.out.println("y is " + y); /* The absolute value of a number is equal to the number if the number is positive or zero and equal to the negative of the number if the number is negative.*/ System.out.println("|" + i + "| is " + Math.abs(i));

System.out.println("|" + j + "| is " + Math.abs(j)); System.out.println("|" + x + "| is " + Math.abs(x)); System.out.println("|" + y + "| is " + Math.abs(y)); /* You can round off a floating point number to the nearest integer with round() */ System.out.println(x + " is approximately " + Math.round(x)); System.out.println(y + " is approximately " + Math.round(y)); /* The "ceiling" of a number is the smallest integer greater than or equal to the number. Every integer is its own ceiling.*/ System.out.println("The ceiling of " + i + " is " + Math.ceil(i)); System.out.println("The ceiling of " + j + " is " + Math.ceil(j)); System.out.println("The ceiling of " + x + " is " + Math.ceil(x)); System.out.println("The ceiling of " + y + " is " + Math.ceil(y)); /* The "floor" of a number is the largest integer less than or equal to the number. Every integer is its own floor.*/ System.out.println("The floor of " + i + " is " + Math.floor(i)); System.out.println("The floor of " + j + " is " + Math.floor(j)); System.out.println("The floor of " + x + " is " + Math.floor(x)); System.out.println("The floor of " + y + " is " + Math.floor(y)); // min() returns the smaller of the two arguments you pass it System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j)); System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y)); System.out.println("min(" + i + "," + x +

") is " + Math.min(i,x)); System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j)); /* There's a corresponding max() method that returns the larger of two numbers */ System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j)); System.out.println("max(" + x + "," + y + ") is " + Math.max(x,y)); System.out.println("max(" + i + "," + x + ") is " + Math.max(i,x)); System.out.println("max(" + y + "," + j + ") is " + Math.max(y,j)); // The Math library defines a couple of useful constants: System.out.println("Pi is " + Math.PI); System.out.println("e is " + Math.E); // Trigonometric methods - All arguments are given in radians // Convert a 45 degree angle to radians double angle = 45.0 * 2.0 * Math.PI/360.0; System.out.println("cos(" + angle + ") is " + Math.cos(angle)); System.out.println("sin(" + angle + ") is " + Math.sin(angle)); // Inverse Trigonometric methods - All values are returned as radians double value = 0.707; System.out.println("acos(" + value + ") is " + Math.acos(value)); System.out.println("asin(" + value + ") is " + Math.asin(value)); System.out.println("atan(" + value + ") is " + Math.atan(value)); // Exponential and Logarithmic Methods // exp(a) returns e (2.71828...) raised to the power of a.

System.out.println("exp(1.0) is " + Math.exp(1.0)); System.out.println("exp(10.0) is " + Math.exp(10.0)); System.out.println("exp(0.0) is " + Math.exp(0.0)); // log(a) returns the natural logarithm (base e) of a. System.out.println("log(1.0) is " + Math.log(1.0)); System.out.println("log(10.0) is " + Math.log(10.0)); System.out.println("log(Math.E) is " + Math.log(Math.E)); // pow(x, y) returns the x raised to the yth power. System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0,2.0)); System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5)); System.out.println("pow(8, -1) is " + Math.pow(8,-1)); // sqrt(x) returns the square root of x. for (i=0; i < 10; i++) { System.out.println("The square root of " + i + " is " + Math.sqrt(i)); } /*Finally there's one Random method that returns a random number between 0.0 and 1.0 */ System.out.println( "Here's one random number: " + Math.random()); System.out.println( "Here's another random number: " + Math.random()); } }

Output i is 7 j is -9 x is 72.3 y is 0.34 |7| is 7 |-9| is 9 |72.3| is 72.3 |0.34| is 0.34 72.3 is approximately 72 0.34 is approximately 0 The ceiling of 7 is 7.0 The ceiling of -9 is -9.0 The ceiling of 72.3 is 73.0 The ceiling of 0.34 is 1.0 The floor of 7 is 7.0 The floor of -9 is -9.0 The floor of 72.3 is 72.0 The floor of 0.34 is 0.0 min(7,-9) is -9 min(72.3,0.34) is 0.34 min(7,72.3) is 7.0 min(0.34,-9) is -9.0 max(7,-9) is 7 max(72.3,0.34) is 72.3 max(7,72.3) is 72.3 max(0.34,-9) is 0.34 Pi is 3.141592653589793 e is 2.718281828459045 cos(0.7853981633974483) is 0.7071067811865476 sin(0.7853981633974483) is 0.7071067811865475 acos(0.707) is 0.7855491633997437 asin(0.707) is 0.785247163395153 atan(0.707) is 0.6154085176292563 exp(1.0) is 2.7182818284590455 exp(10.0) is 22026.465794806718 exp(0.0) is 1.0 log(1.0) is 0.0 log(10.0) is 2.302585092994046 log(Math.E) is 1.0 pow(2.0, 2.0) is 4.0 pow(10.0, 3.5) is 3162.2776601683795 pow(8, -1) is 0.125 The square root of 0 is 0.0

The square root of 1 is 1.0 The square root of 2 is 1.4142135623730951 The square root of 3 is 1.7320508075688772 The square root of 4 is 2.0 The square root of 5 is 2.23606797749979 The square root of 6 is 2.449489742783178 The square root of 7 is 2.6457513110645907 The square root of 8 is 2.8284271247461903 The square root of 9 is 3.0 Here's one random number: 0.6635323726430744 Here's another random number: 0.293932289452723 The Math class is final and these methods are static. This means you cannot subclass Math and create modified versions of these methods. This is probably a good thing, as it reduces the possibility of ambiguity. abs Thus the following will simply print out 10. If the number is not negative you just get back the same number. System.out.println(Math.abs(-10)); Code public class Test93 { public static void main(String[] args) { System.out.println(Math.floor(-10.6)); System.out.println(Math.floor(-11.22)); System.out.println(Math.floor(88)); System.out.println(Math.floor(-10.01)); System.out.println(Math.floor(11.6)); } } Output -11.0 -12.0 88.0 -11.0 11.0

max and min Take note of the following two methods as they take two parameters. You may get questions with faulty examples that pass them only one parameter. As you might expect these methods are the equivalents of "which is the largest THIS parameter or THIS parameter" Code public class Test94 { public static void main(String args[]) { System.out.println(Math.max(-2,-3)); System.out.println(Math.max(4,5)); System.out.println(Math.min(3,3)); System.out.println(Math.min(-11,-8)); System.out.println(Math.min(3,5)); } } Output -2 5 3 -11 3 random Returns a random number between 0.0 and 1.0. Unlike some random number system Java does not appear to offer the ability to pass a seed number to increase the randomness. This method can be used to produce a random number between 0 and 100 as follows. For the purpose of the exam one of the important aspects of this method is that the value returned is between 0.0 and 1.0. Thus a typical sequence of output might be 0.9151633320773057 0.25135231957619386 0.10070205341831895

Often a program will want to produce a random number between say 0 and 10 or 0 and 100. The following code combines math code to produce a random number between 0 and 100. System.out.println(Math.round(Math.random()*100)); round Rounds to the nearest integer. So, if the value is more than half way towards the higher integer, the value is rounded up to the next Integer. If the number is less than this the next lowest integer is returned. So for example if the input to round is x then : 2.0 <=x < 2.5. then Math.round(x)==2.0 2.5 <=x < 3.0 the Math.round(x)==3.0 Here are some samples with output System.out.println(Math.round(1.01)); System.out.println(Math.round(-2.1)); System.out.println(Math.round(20)); 1 -2 20 sin cos tan These trig methods take a parameter of type double and do just about what trig functions do in every other language you have used. So the thing to remember is that the parameter is a double. sqrt returns a double value that is the square root of the parameter. Summary 1. 2. 3. 4. max and min take two parameters random returns value between 0 and 1 abs chops of the sign component round rounds to the nearest integer but leaves the sign

Collection API

-

The Collection API is nothing but a set of data structures in Java. There are standard interfaces and implementation class and all the collections vary according to a) the storage mechanism used b) in the way they can access data and c) in the rules about what the date might be stored.

-

The java.util.Collections Class is the main class, which provides static methods, which operate on Collections or return a Collection. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection. The general interface java.util.Collection defines the basic framework for all collections. This interface has methods that add item into the collection, remove items from the collection, determine whether the items are in the collection and count the number of items in the collection. A simple collection places no constraints on the type of elements, order of elements or repetition of elements within the collection. A collection in which items are ordered (e.g., in the order in which they are added) is known as a List. A List is ordered and does not reject duplicates. A collection in which the condition is that it cannot contain the same value more than once, it is known as a Set. A Set has no special order but rejects duplicates. The final type of specialized behavior directly supported by the Collection API is known as a Map. In a Map, it uses the set of key values to look up or index the stored date. IMP: List, Set and Map Interface extend the Collection Interface.

-

-

-

The old collections The Java 2 API includes new interfaces and classes to enhance the collections available. Earlier versions of Java included

1. 2. 3. 4.

Vector Hashtable Array BitSet

The new collections At the root of the Collection API is the Collection interface. This gives you a series of common methods that all collection classes will have. You would probably never create your own class that implements Collection as Java supplies a series of sub-interfaces and classes that uses the Collection interface. The Java2 API includes the following new collection interfaces Sets Lists Maps Classes that implement the Collection interface store objects as elements rather than primitives. This approach has the drawback that creating objects has a performance overhead and the elements must be cast back from Object to the appropriate type before being used. It also means that the collections do not check that the elements are all of the same type, as an object can be just about anything. A Set A Set is a collection interface that cannot contain duplicate elements. It thus matches nicely onto concepts such as a record set returned from a relational database. Part of the magic of the Set interface is in the add method. add(Object o) Any object passed to the add method must implement the equals method so the value can be compared with existing objects in the class. If the set already contains this object the call to add leaves the set unchanged and returns false. The idea of returning false when attempting to add an element seems more like the approach used in C/C++ than Java. Most similar java methods would seem to throw an Exception in this type of situation. A List A list is a sorted collection interface that can contain duplicates

Some important methods are 1. add 2. remove 3. clear 4. The JDK documentation gives the example of using List to manage an actual GUI list control containing a list of the names of the Planets. A Map Map is an interface, classes that implement it cannot contain duplicate keys, and it is similar to a Hashtable. Why use Collections instead of arrays? The big advantage of the collections over arrays is that the collections are growable, you do not have to assign the size at creation time. The drawback of collections is that they only store objects and not primitives and this comes with an inevitable performance overhead. Arrays do not directly support sorting, but this can be overcome by using the static methods of the Collections. Here is an example. Code import java.util.*; public class Test95 { public static void main(String argv[]) { Test95 s = new Test95(); } Test95() { String s[] = new String[4]; s[0]="z"; s[1]="b"; s[2]="c"; s[3]="a"; Arrays.sort(s); for(int i=0;i< s.length;i++) { System.out.println(s[i]);

} } } Output a b c z Set and Map collections ensure uniqueness, List Collections do not ensure uniqueness but they are sorted (ordered). Using Hashtable Hashtable are a little like the Visual Basic concept of a Collection used with a key. It acts like a Vector, except that instead of referring to elements by number, you refer to them by key. The hash part of the name refers to a math term dealing with creating indexes. A Hashtable can offer the benefit over a Vector of faster look ups. BitSet A BitSet as its name implies, stores a sequence of Bits. Don't be misled by the "set" part of its name is not a set in the mathematical or database sense, nor is it related to the Sets available in Java2. It is more appropriate to think of it as a bit vector. A BitSet may useful for the efficient storage of bits where the bits are used to represent true/false values. The alternative of using some sort of collection containing Boolean values can be less efficient. This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations. By default, all bits in the set initially have the value false. Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.

The constructor of a BitSet take int bits wherein it creates a bit set whole initial size is large enough to explicitly represent bits with indices in the range 0 through bits-1. Also it has a default constructor.

Sign up to vote on this title
UsefulNot useful