Java/Collections Data Structure/Vector
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Adaptive extension of the java.util.Vector class
- 2 Append all elements of other Collection to Java Vector
- 3 Copy all elements of Java Vector to an Object Array
- 4 Copy Elements of One Java Vector to Another Java Vector
- 5 Copy Elements of Vector to Java ArrayList
- 6 Count distinct elements in a Vector
- 7 Create Java ArrayList From Enumeration
- 8 Create Vector test
- 9 Enumerate through a Vector using Java Enumeration
- 10 Finding elements in a vector
- 11 Find maximum element of Java Vector
- 12 Find Minimum element of Java Vector
- 13 Find Vector
- 14 Generic Vector with String
- 15 Get Enumeration over Java Vector
- 16 Get Size of Java Vector and loop through the elements
- 17 Get Sub List of Java Vector Example
- 18 Insert all elements of other Collection to Specified Index of Java Vector
- 19 Iterate through elements Java Vector using Iterator
- 20 Iterate through elements Java Vector using ListIterator
- 21 Iterator out of Vector
- 22 Perform Binary Search on Java Vector
- 23 Remove all elements from Java Vector
- 24 Remove an element from specified index of Java Vector
- 25 Remove Element in Vector
- 26 Remove specified element from Java Vector
- 27 Replace All Elements Of Java Vector
- 28 Replace all occurrences of specified element of Java Vector
- 29 Replace an element at specified index of Java Vector
- 30 Reverse order of all elements of Java Vector
- 31 Save Vector to file
- 32 Search an element of Java Vector
- 33 Search an element of Java Vector from specific index
- 34 Sequence
- 35 Serializing a vector
- 36 Set size of Java Vector Example
- 37 Shuffle elements of Java Vector
- 38 Sort elements of Java Vector
- 39 Sort Java Vector in descending order using comparator
- 40 Swap elements of Java Vector
- 41 Unmodifiable Vector Adapter
- 42 Use Vector in java.util
- 43 Vector Util
Adaptive extension of the java.util.Vector class
//revised from marf
import java.util.Vector;
import java.util.Collection;
import java.util.List;
/**
* <p>Adaptive extension of the java.util.Vector class.</p>
*
* <p>You may access elements of a Vector beyond it"s initial length --- the Vector
* will be automaticall adjusted as appropriate.</p>
*
* <p>Useful in the applications where desirable vector"s growth by setting an element
* beyond its upper boundary automatticaly lengthens the vector to accomondate the
* change (similar to Perl arrays).</p>
*
* <p>Similarly, getting an element beyond the upper boundary is not desirable failure, but
* an empty element returned. This makes the application to see as vector of a theoretically infinite
* in length.</p>
*
* TODO: allow negative index boundaries.
*
* $Id: FreeVector.java,v 1.12 2005/08/11 00:44:50 mokhov Exp $
*
* @author Serguei Mokhov
* @version $Revision: 1.12 $
* @since 0.3.0.1
*/
public class FreeVector
extends Vector
{
/**
* For serialization versioning.
* When adding new members or make other structural
* changes regenerate this number with the
* <code>serialver</code> tool that comes with JDK.
* @since 0.3.0.4
*/
private static final long serialVersionUID = 8706834105778495182L;
/**
* A free vector with default capacity as specified by java.util.Vector.
*/
public FreeVector()
{
super();
}
/**
* Constructs this vector given capacity other than default.
* Inherited from java.util.Vector.
* @param piInitialCapacity initial element capacity (number of object placeholders)
*/
public FreeVector(int piInitialCapacity)
{
super(piInitialCapacity);
}
/**
* Constructs this vector given capacity and its increment.
* Inherited from java.util.Vector.
* @param piInitialCapacity initial element capacity (number of object placeholders)
* @param piCapacityIncrement when current capacity reached, until how much capacity should be extened
*/
public FreeVector(int piInitialCapacity, int piCapacityIncrement)
{
super(piInitialCapacity, piCapacityIncrement);
}
/**
* Constructs this vector out of a collection.
* Inherited from java.util.Vector.
* @param poCollection collection for the vector elements.
*/
public FreeVector(Collection poCollection)
{
super(poCollection);
}
/**
* Access an element of the vector given index.
* Overridden from java.util.Vector.
* @param piIndex vector element index to retrieve
* @return object cotained at specified index, null if beyond boundary
*/
public Object elementAt(int piIndex)
{
if(piIndex > size() - 1)
return null;
return super.elementAt(piIndex);
}
/**
* Set an element of the vector given index.
* Capacity is always ensured to be able to accomodate
* any positive inidex (barring out of memory problems).
* Overridden from java.util.Vector.
*
* @param poElement element to set at the index
* @param piIndex the index
*/
public void setElementAt(Object poElement, int piIndex)
{
ensureIndexCapacity(piIndex);
super.setElementAt(poElement, piIndex);
}
/**
* Inserts an element of the vector after given index.
* Capacity is always ensured to be able to accomodate
* any positive inidex (barring out of memory problems).
* Overridden from java.util.Vector.
*
* @param poElement element to set after the index
* @param piIndex the index
*/
public void insertElementAt(Object poElement, int piIndex)
{
ensureIndexCapacity(piIndex);
super.insertElementAt(poElement, piIndex);
}
/**
* Make sure the capacity of the vector is enough
* to hold an element with the specified index.
* Has effect only if the index is greater than
* the current vector"s size.
*
* @param piIndex the index to accomodate
*/
public void ensureIndexCapacity(int piIndex)
{
if(piIndex > size() - 1)
{
ensureCapacity(piIndex + 1);
setSize(piIndex + 1);
}
}
/**
* Access an element of the vector given index.
* Overridden from java.util.Vector. Calls the overridden elementAt().
*
* @param piIndex vector element index to retrieve
* @return object cotained at specified index, null if beyond boundary
*/
public synchronized Object get(int piIndex)
{
return elementAt(piIndex);
}
/**
* Set an element of the vector given index.
* Capacity is always ensured to be able to accomodate
* any positive inidex (barring out of memory problems).
* Overridden from java.util.Vector.
*
* @param poElement element to set at the index
* @param piIndex the index
* @return object that was previously at that index.
*/
public synchronized Object set(int piIndex, Object poElement)
{
Object oOldElement = elementAt(piIndex);
setElementAt(poElement, piIndex);
return oOldElement;
}
/**
* Adds an element of the vector at the specified index.
* Overridden from java.util.Vector. Calls the overridden insertElementAt().
* @param piIndex the index
* @param poElement element to set after the index
*/
public synchronized void add(int piIndex, Object poElement)
{
insertElementAt(poElement, piIndex);
}
/**
* Removes an element at index.
* If the index is beyond the upper boundary, returns null.
* Overrides java.util.Vector.
* @param piIndex index of the element to be removed
* @return object reference of the element just removed; null if index exceeds the upper bound
*/
public synchronized Object remove(int piIndex)
{
if(piIndex >= size())
{
//???
// 1 less than the index
//ensureIndexCapacity(piIndex - 1);
return null;
}
return super.remove(piIndex);
}
/**
* Adds a collection of elements to this vector starting at given index.
* Makes sure the capacity of the current vector reaches the piIndex.
* Overrides java.util.Vector.
*
* @param piIndex starting index to add elements from
* @param poCollection collection of elements to add
*
* @return <code>true</code> if the vector has changed
*/
public synchronized boolean addAll(int piIndex, Collection poCollection)
{
ensureIndexCapacity(piIndex);
return super.addAll(piIndex, poCollection);
}
/**
* Retrieves a sublist subset of vector elements given index boundaries.
* Makes sure the capacity of the current vector reaches the piToIndex.
* Overrides java.util.Vector.
*
* @param piFromIndex starting index to fetch elements from
* @param piToIndex last index to fetch elements to
*
* @return a corresponding List reference.
*/
public synchronized List subList(int piFromIndex, int piToIndex)
{
ensureIndexCapacity(piToIndex);
return super.subList(piFromIndex, piToIndex);
}
/**
* Not implemented.
* Meant to remove a set of elements between two specified indices.
* @param piFromIndex starting index to remove elements from
* @param piToIndex last index to remove elements to
* @throws NotImplementedException
*/
public synchronized void removeRange(int piFromIndex, int piToIndex)
{
// TODO: implement
throw new RuntimeException( "removeRange()");
}
/**
* Retrieves class" revision.
* @return revision string
* @since 0.3.0.2
*/
public static String getMARFSourceCodeRevision()
{
return "$Revision: 1.12 $";
}
}
// EOF
Append all elements of other Collection to Java Vector
import java.util.Vector;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("4");
arrayList.add("5");
v.addAll(arrayList);
for (int i = 0; i < v.size(); i++){
System.out.println(v.get(i));
}
}
}
Copy all elements of Java Vector to an Object Array
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
Object[] objArray = new Object[5];
v.copyInto(objArray);
for (Object obj: objArray){
System.out.println(obj);
}
}
}
Copy Elements of One Java Vector to Another Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v1 = new Vector<String>();
v1.add("1");
v1.add("2");
v1.add("3");
Vector<String> v2 = new Vector<String>();
v2.add("One");
v2.add("Two");
v2.add("Three");
v2.add("Four");
v2.add("Five");
System.out.println(v2);
Collections.copy(v2, v1);
System.out.println(v2);
}
}
/*[One, Two, Three, Four, Five]
[1, 2, 3, Four, Five]
*/
Copy Elements of Vector to Java ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("One");
arrayList.add("Two");
arrayList.add("Three");
arrayList.add("Four");
arrayList.add("Five");
System.out.println(arrayList);
Collections.copy(arrayList, v);
System.out.println(arrayList);
}
}
/*
[One, Two, Three, Four, Five]
[1, 2, 3, Four, Five]
*/
Count distinct elements in a Vector
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] argv) {
List<String> list = new ArrayList<String>();
list.add("A");
list.add("2");
list.add("c2");
System.out.println(countDistinctElements(list, 0, list.size()));
}
static int countDistinctElements(List source, int position, int count){
List list = source.subList(position, position + count);
Set set = new HashSet();
set.addAll(list);
return set.size();
}
}
Create Java ArrayList From Enumeration
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("A");
v.add("B");
v.add("D");
v.add("E");
v.add("F");
System.out.println(v);
Enumeration e = v.elements();
ArrayList<String> aList = Collections.list(e);
System.out.println(aList);
}
}
/*
[A, B, D, E, F]
[A, B, D, E, F]
*/
Create Vector test
import java.util.Vector;
public class CreateVector {
public static void main(String args[]) {
{
Vector v = new Vector(0);
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
}
{
Vector v = new Vector();
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
v.addElement("Hello");
System.out.println(v.capacity());
}
}
}
Enumerate through a Vector using Java Enumeration
import java.util.Enumeration;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("One");
v.add("Two");
v.add("Three");
v.add("Four");
Enumeration e = v.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Finding elements in a vector
import java.util.Vector;
public class FindVector {
public static void main(String args[]) {
String data[] = { "Java", "Source", "and", "Support", "."};
Vector v = new Vector();
for (int i = 0, n = data.length; i < n; i++) {
v.add(data[i]);
}
System.out.println(v);
System.out.println("Contains Java?: " + v.contains("Java"));
System.out.println("Contains jexp?: " + v.contains("jexp"));
System.out.println("Where"s and?: " + v.indexOf("and"));
System.out.println("Where"s Source?: " + v.indexOf("Source"));
System.out.println("Where"s Java from end?: "
+ v.lastIndexOf("Java"));
}
}
Find maximum element of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<Double> v = new Vector<Double>();
v.add(new Double("3.4324"));
v.add(new Double("3.3532"));
v.add(new Double("3.342"));
v.add(new Double("3.349"));
v.add(new Double("2.3"));
Object obj = Collections.max(v);
System.out.println(obj);
}
}
//3.4324
Find Minimum element of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<Double> v = new Vector<Double>();
v.add(new Double("3.4"));
v.add(new Double("3.3"));
v.add(new Double("4.4"));
v.add(new Double("5.3"));
v.add(new Double("3.3"));
Object obj = Collections.min(v);
System.out.println(obj);
}
}
Find Vector
import java.util.Vector;
public class FindVector2 {
static String members[] = { "Ralph", "Waldo", "Emerson", "Henry", "David",
"Thoreau", "Walden", "Pond", "Thoreau", "Institute" };
public static void main(String args[]) {
Vector v = new Vector();
for (int i = 0, n = members.length; i < n; i++) {
v.add(members[i]);
}
System.out.println(v);
System.out.println("Contains Society?: " + v.contains("Society"));
System.out.println("Contains Waldo?: " + v.contains("Waldo"));
System.out.println("Where"s Waldo?: " + v.indexOf("Waldo"));
System.out.println("Where"s Thoreau?: " + v.indexOf("Thoreau"));
System.out.println("Where"s Thoreau from end?: "
+ v.lastIndexOf("Thoreau"));
int index = 0;
int length = v.size();
while ((index < length) && (index >= 0)) {
index = v.indexOf("Thoreau", index);
if (index != -1) {
System.out.println(v.get(index));
index++;
}
}
}
}
Generic Vector with String
import java.util.Vector;
public class MainClass {
static void addCode(String code) {
if (!list.contains(code)) {
list.add(code);
}
}
static Vector<String> list;
public static void main(String[] arguments) {
String[] codes = { "alpha", "lambda", "gamma", "delta", "zeta" };
list = new Vector<String>();
for (int i = 0; i < codes.length; i++) {
addCode(codes[i]);
}
for (int j = 0; j < codes.length; j++) {
addCode(codes[j]);
}
for (String code : list) {
System.out.println(code);
}
}
}
Get Enumeration over Java Vector
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("A");
v.add("B");
v.add("D");
v.add("E");
v.add("F");
Enumeration e = Collections.enumeration(v);
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Get Size of Java Vector and loop through the elements
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
System.out.println( v.size());
for (String str: v){
System.out.println(str);
}
}
}
Get Sub List of Java Vector Example
import java.util.List;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
List lst = v.subList(1, 3);
for (String str : v) {
System.out.println(str);
}
Object obj = lst.remove(0);
for (String str : v) {
System.out.println(str);
}
}
}
Insert all elements of other Collection to Specified Index of Java Vector
import java.util.ArrayList;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("4");
arrayList.add("5");
v.addAll(1, arrayList);
for (String str: v)
System.out.println(str);
}
}
Iterate through elements Java Vector using Iterator
import java.util.Iterator;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
Iterator itr = v.iterator();
while (itr.hasNext()){
System.out.println(itr.next());
}
}
}
Iterate through elements Java Vector using ListIterator
import java.util.ListIterator;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
ListIterator itr = v.listIterator();
while (itr.hasNext()){
System.out.println(itr.next());
}
while (itr.hasPrevious()){
System.out.println(itr.previous());
}
}
}
Iterator out of Vector
import java.util.Iterator;
import java.util.Vector;
public class Main {
public static void main(String[] arguments) {
String[] codes = { "alpha", "lambda", "gamma", "delta", "zeta" };
Vector list = new Vector();
for (int i = 0; i < codes.length; i++) {
if (!list.contains(codes[i])) {
list.add(codes[i]);
}
}
for (Iterator ite = list.iterator(); ite.hasNext();) {
String output = (String) ite.next();
System.out.println(output);
}
}
}
Perform Binary Search on Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("Z");
v.add("B");
v.add("D");
v.add("E");
v.add("F");
Collections.sort(v);
System.out.println(v);
int index = Collections.binarySearch(v, "D");
System.out.println("Element found at : " + index);
}
}
/*[B, D, E, F, Z]
Element found at : 1
*/
Remove all elements from Java Vector
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
System.out.println(v.size());
v.clear();
// OR v.removeAllElements();
System.out.println(v.size());
}
}
Remove an element from specified index of Java Vector
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
Object obj = v.remove(1);
System.out.println(obj + " is removed from Vector");
for (String str: v)
System.out.println(str);
v.removeElementAt(2);
for (String str: v)
System.out.println(str);
}
}
Remove Element in Vector
import java.util.Vector;
public class RemoveVector {
static boolean removeAll(Vector v, Object e) {
Vector v1 = new Vector();
v1.add(e);
return v.removeAll(v1);
}
public static void main (String args[]) {
Vector v = new Vector();
for (int i=0, n=args.length; i<n; i++) {
v.add(args[i]);
}
System.out.println(removeAll(v, args[0]));
System.out.println(v);
}
}
Remove specified element from Java Vector
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
System.out.println(v.remove("2"));
for (String str: v){
System.out.println(str);
}
System.out.println(v.removeElement("3"));
for (String str: v){
System.out.println(str);
}
}
}
Replace All Elements Of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("A");
v.add("B");
v.add("D");
System.out.println(v);
Collections.fill(v, "REPLACED");
System.out.println(v);
}
}
/*
[A, B, D]
[REPLACED, REPLACED, REPLACED]
*/
Replace all occurrences of specified element of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("A");
v.add("B");
v.add("A");
v.add("C");
v.add("D");
System.out.println(v);
Collections.replaceAll(v, "A", "Replace All");
System.out.println(v);
}
}
Replace an element at specified index of Java Vector
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.set(1, "REPLACED ELEMENT");
for (String str : v) {
System.out.println(str);
}
}
}
Reverse order of all elements of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("A");
v.add("B");
v.add("C");
v.add("D");
v.add("E");
System.out.println(v);
Collections.reverse(v);
System.out.println(v);
}
}
/*
[A, B, C, D, E]
[E, D, C, B, A]
*/
Save Vector to file
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
public class SaveVector1 {
public static void main(String args[]) throws Exception {
Vector v = new Vector(Arrays.asList(args));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(v);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Vector v2 = (Vector) ois.readObject();
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
Search an element of Java Vector
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
v.add("1");
v.add("2");
System.out.println(v.contains("3"));
System.out.println(v.indexOf("5"));
System.out.println(v.lastIndexOf("2"));
}
}
Search an element of Java Vector from specific index
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
v.add("1");
v.add("2");
System.out.println(v.indexOf("1", 4));
System.out.println(v.lastIndexOf("2", 5));
}
}
Sequence
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;
public class Sequence {
public static void main(String args[]) throws IOException {
Vector v = new Vector(3);
v.add(new FileInputStream("/etc/motd"));
v.add(new FileInputStream("foo.bar"));
v.add(new FileInputStream("/temp/john.txt"));
Enumeration e = v.elements();
SequenceInputStream sis = new SequenceInputStream(e);
InputStreamReader isr = new InputStreamReader(sis);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
Serializing a vector
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
public class SaveVector {
public static void main(String args[]) throws Exception {
String data[] = { "Java", "Source", "and", "Support", "."};
Vector v = new Vector(Arrays.asList(data));
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(v);
o.close();
ByteArrayInputStream bb = new ByteArrayInputStream(b.toByteArray());
ObjectInputStream oo = new ObjectInputStream(bb);
Vector v2 = (Vector) oo.readObject();
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
Set size of Java Vector Example
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
v.setSize(3);
for (String str : v) {
System.out.println(str);
}
v.setSize(5);
for (String str : v) {
System.out.println(str);
}
}
}
Shuffle elements of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
System.out.println(v);
Collections.shuffle(v);
System.out.println(v);
}
}
/*[1, 2, 3, 4, 5]
[5, 4, 1, 3, 2]
*/
Sort elements of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("3");
v.add("5");
v.add("2");
v.add("4");
Collections.sort(v);
for (String str : v){
System.out.println(str);
}
}
}
Sort Java Vector in descending order using comparator
import java.util.Collections;
import java.util.ruparator;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
Comparator comparator = Collections.reverseOrder();
System.out.println(v);
Collections.sort(v, comparator);
System.out.println(v);
}
}
Swap elements of Java Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
System.out.println(v);
Collections.swap(v, 0, 4);
System.out.println(v);
}
}
Unmodifiable Vector Adapter
/*
* $Id: UnmodifiableVectorAdapter.java,v 1.1.1.1 2005/04/07 18:36:25 pocho Exp $
*/
import java.util.Collection;
import java.util.List;
import java.util.Vector;
/**
* Adapter that adapts any {@link java.util.List} to {@link java.util.Vector} class.
*
* @version $Name: $ - $Revision: 1.1.1.1 $ - $Date: 2005/04/07 18:36:25 $
*/
public class UnmodifiableVectorAdapter extends Vector {
private List adaptedList;
public UnmodifiableVectorAdapter(List list) {
setAdaptedList(list);
}
public void setAdaptedList(List list) {
this.adaptedList = list;
}
public boolean contains(Object elem) {
return adaptedList.contains(elem);
}
public boolean containsAll(Collection c) {
return adaptedList.containsAll(c);
}
public Object elementAt(int index) {
return adaptedList.get(index);
}
public Object get(int index) {
return adaptedList.get(index);
}
public int indexOf(Object elem) {
return adaptedList.indexOf(elem);
}
public int indexOf(Object elem, int index) {
return subList(index, size()).indexOf(elem);
}
public boolean isEmpty() {
return adaptedList.isEmpty();
}
public Object lastElement() {
return adaptedList.get(size() - 1);
}
public int lastIndexOf(Object elem) {
return adaptedList.lastIndexOf(elem);
}
public int lastIndexOf(Object elem, int index) {
return subList(0, index).indexOf(elem);
}
public int size() {
return adaptedList.size();
}
public List subList(int fromIndex, int toIndex) {
return adaptedList.subList(fromIndex, toIndex);
}
public Object[] toArray() {
return adaptedList.toArray();
}
public Object[] toArray(Object[] a) {
return adaptedList.toArray(a);
}
public String toString() {
return adaptedList.toString();
}
public void add(int index, Object element) {
throw new UnsupportedOperationException();
}
public boolean add(Object o) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection c) {
throw new UnsupportedOperationException();
}
public boolean addAll(int index, Collection c) {
throw new UnsupportedOperationException();
}
public void addElement(Object obj) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
public Object clone() {
throw new UnsupportedOperationException();
}
public void insertElementAt(Object obj, int index) {
throw new UnsupportedOperationException();
}
public Object remove(int index) {
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection c) {
throw new UnsupportedOperationException();
}
public void removeAllElements() {
throw new UnsupportedOperationException();
}
public boolean removeElement(Object obj) {
throw new UnsupportedOperationException();
}
public void removeElementAt(int index) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection c) {
throw new UnsupportedOperationException();
}
public Object set(int index, Object element) {
throw new UnsupportedOperationException();
}
public void setElementAt(Object obj, int index) {
throw new UnsupportedOperationException();
}
public void setSize(int newSize) {
throw new UnsupportedOperationException();
}
}
Use Vector in java.util
import java.util.Vector;
public class VectorBenchmark1 {
public static final int MaxSize = 100000;
public static final int NTRIES = 10;
public static void main(String[] args) {
Vector v = new Vector();
long start = System.currentTimeMillis();
for (int i = 0; i < MaxSize; i++)
v.add(new Integer(i));
long end = System.currentTimeMillis();
System.out.println("Allocating vector elements: " + (end - start)
+ " milliseconds");
Integer[] integerArray = new Integer[1];
start = System.currentTimeMillis();
for (int i = 0; i < MaxSize; i++) {
if (i >= integerArray.length) {
Integer[] b = new Integer[i * 2];
System.arraycopy(integerArray, 0, b, 0, integerArray.length);
integerArray = b;
}
integerArray[i] = new Integer(i);
}
end = System.currentTimeMillis();
System.out.println("Allocating array elements: " + (end - start)
+ " milliseconds");
start = System.currentTimeMillis();
for (int j = 0; j < NTRIES; j++)
for (int i = 0; i < MaxSize; i++) {
Integer r = (Integer) v.get(i);
v.set(i, new Integer(r.intValue() + 1));
}
end = System.currentTimeMillis();
System.out.println("Accessing vector elements: " + (end - start)
+ " milliseconds");
start = System.currentTimeMillis();
for (int j = 0; j < NTRIES; j++)
for (int i = 0; i < MaxSize; i++) {
Integer r = integerArray[i];
integerArray[i] = new Integer(r.intValue() + 1);
}
end = System.currentTimeMillis();
System.out.println("Accessing array elements: " + (end - start)
+ " milliseconds");
}
}
Vector Util
/*
Software Architecture Design Patterns in Java
by Partha Kuchana
Auerbach Publications
*/
import java.util.Vector;
public class MiscUtil {
public static boolean hasDuplicates(Vector v) {
int i = 0;
int j = 0;
boolean duplicates = false;
for (i = 0; i < v.size() - 1; i++) {
for (j = (i + 1); j < v.size(); j++) {
if (v.elementAt(i).toString().equalsIgnoreCase(
v.elementAt(j).toString())) {
duplicates = true;
}
}
}
return duplicates;
}
public static Vector removeDuplicates(Vector s) {
int i = 0;
int j = 0;
boolean duplicates = false;
Vector v = new Vector();
for (i = 0; i < s.size(); i++) {
duplicates = false;
for (j = (i + 1); j < s.size(); j++) {
if (s.elementAt(i).toString().equalsIgnoreCase(
s.elementAt(j).toString())) {
duplicates = true;
}
}
if (duplicates == false) {
v.addElement(s.elementAt(i).toString().trim());
}
}
return v;
}
public static Vector removeDuplicateDomains(Vector s) {
int i = 0;
int j = 0;
boolean duplicates = false;
String str1 = "";
String str2 = "";
Vector v = new Vector();
for (i = 0; i < s.size(); i++) {
duplicates = false;
for (j = (i + 1); j < s.size(); j++) {
str1 = "";
str2 = "";
str1 = s.elementAt(i).toString().trim();
str2 = s.elementAt(j).toString().trim();
if (str1.indexOf("@") > -1) {
str1 = str1.substring(str1.indexOf("@"));
}
if (str2.indexOf("@") > -1) {
str2 = str2.substring(str2.indexOf("@"));
}
if (str1.equalsIgnoreCase(str2)) {
duplicates = true;
}
}
if (duplicates == false) {
v.addElement(s.elementAt(i).toString().trim());
}
}
return v;
}
public static boolean areVectorsEqual(Vector a, Vector b) {
if (a.size() != b.size()) {
return false;
}
int i = 0;
int vectorSize = a.size();
boolean identical = true;
for (i = 0; i < vectorSize; i++) {
if (!(a.elementAt(i).toString().equalsIgnoreCase(b.elementAt(i)
.toString()))) {
identical = false;
}
}
return identical;
}
public static Vector removeDuplicates(Vector a, Vector b) {
int i = 0;
int j = 0;
boolean present = true;
Vector v = new Vector();
for (i = 0; i < a.size(); i++) {
present = false;
for (j = 0; j < b.size(); j++) {
if (a.elementAt(i).toString().equalsIgnoreCase(
b.elementAt(j).toString())) {
present = true;
}
}
if (!(present)) {
v.addElement(a.elementAt(i));
}
}
return v;
}
}// end of class