Documente Academic
Documente Profesional
Documente Cultură
- 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:-
Vector Constructors
- Vector () –Constructs an empty vector so that its internal data array has size
10 and its standard capacity increment is zero.
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
Code
import java.util.*;
class Test89
{
public static void main(String args[])
{
// Create a vector and its elements
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));
v.insertElementAt(s, 1);
System.out.println(v);
System.out.println(v);
// Elements in a Vector
System.out.println(v.size());
}
}
Output
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[])
{
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);
System.out.println(i);
System.out.println(f);
}
}
Output
Code
import java.util.Vector;
class Test91
{
String ename;
Integer sal;
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 defines the method by which you can enumerate
(obtain one at a time) the elements in a collection of objects.
boolean hasMoreElements()
Tests if this enumeration contains more elements.
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;
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.
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).
2) 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).
4) static double sqrt (double a) – This returns the square root of the
double parameter.
Code
class MathExample
{
public static void main(String args[])
{
int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;
/* You can round off a floating point number to the nearest integer
with round() */
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));
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));
System.out.println("cos(" + angle +
") is " + Math.cos(angle));
System.out.println("sin(" + angle +
") is " + Math.sin(angle));
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));
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));
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
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
Code
Output
-2
5
3
-11
3
random
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 :
System.out.println(Math.round(1.01));
System.out.println(Math.round(-2.1));
System.out.println(Math.round(20));
1
-2
20
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
Summary
- 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
- 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 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 Java 2 API includes new interfaces and classes to enhance the collections
available. Earlier versions of Java included
1. Vector
2. Hashtable
3. Array
4. BitSet
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.
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
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
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.
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.*;
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.