Java Programming class – Department of Network

advertisement
Java Programming
Mehdi Ebady Manaa
3rd class – Department of Network
College of IT- University of Babylon
1. Vectors in Java
Vectors are extensible arrays, they are empty when first
created and can grow and shrink on high end. Vectors are
defined in java.util package.
The general specifications of vectors in java are: Values from primitive data types like int, char and
Boolean cannot be stored in Vectors.
 Primitive values can be used in contexts requiring
objects by wrapping them in objects (Wrapper
Classes).
 Each primitive type has an associated object type.
Eg: Integerint, Character char.
 Contains elements numbered from zero up to length1.
 Length can be determined by size method.
 Each element in vector has the apparent type of
Object  heterogeneous: diff elements of a vector
can be objects of diff types.
 When created, vector is empty. Its length = 0.
Vector v = new Vector();
System.out.println(v.size());
 Add element in vector:
v.add(“abc”);
[0]
“abc”
v
 Vector elements can be accessed for legal indices. Use
gets method to access the indexed element.
Page 1
Date: December 2, 2014
Java Programming
Mehdi Ebady Manaa
3rd class – Department of Network
College of IT- University of Babylon
String s = (String)v.get(0);
index
 Method get returns an Object. Cast the result to the
respective type.
 To change element in a vector, use set method. Eg:
v.set(0, “def”); // set “def” in index 0
 Elements in vectors must be of types that are subtypes of
Object.
 Vectors cannot contain elements of primitive data types
such as int and char.
 You can use associated object types.
v.add(3);
// illegal
v.add(new Integer(3)); //legal
Page 2
Date: December 2, 2014
Java Programming
Mehdi Ebady Manaa
3rd class – Department of Network
College of IT- University of Babylon
Example: 1
import java.util.Vector;
public class Q4Vectoreven {
public static void main (String args[])
{
Vector v= new Vector ();
for (int i=0; i<=9; i++){
v.add(i);
}
for (int j=0; j< v.size()-1;j++)
{
if (j%2!=0)
{
v.set((Integer)v.get(j), " ");
}
}
for (int k=0; k<v.size()-1; k++)
{
System.out.println(v.get(k));
}
}
}
Example: 2: Convert Elements of Vector to an Array
import java.util.Vector;
public class SortJavaVectorExample {
public static void main(String[] args) {
int tem=0;
//create Vector object
Vector<Integer> vec = new Vector<Integer>(4);
Integer[] anArray = new Integer[4];
//Add elements to Vector
vec.add(31);
vec.add(2);
vec.add(3);
vec.add(-10);
vec.add(-20);
int kk=0;
System.out.print(" The element before sorting are
for(int i=0; i<vec.size()-1; i++)
{
anArray[i]= (Integer) vec.get(i);
System.out.print(anArray[i]+" ");
:" );
}
}
}
Page 3
Date: December 2, 2014
Download