Perry Smith

Java Questions & Answers

Home / Java Q & A Archive Page 1 / Java Q & A Archive / Java Q & A Main Page

9-1-98

I want to create an array with an undefined number of elements, to hold lines of a file of an unknown length. Does anyone know of a good way to do this???

Mike


Response
9-4-98

The Vector class is part of the java.util package of the Java API. It provides a service similar to an array in that it can store a list of values and reference them by an index. An array remains a fixed size throughout its existence, but a Vector object can dynamically grow and shrink as needed.

Look at information regarding vectors, I suspect that vectors are part of the puzzle.

Maybe someone else will come along and provide us with more information regarding this matter.

Perry Smith


9-13-98

P. Smith's suggestion is the route I would take, so I'll elaborate.

You import the Vector API w/ "import java.util.Vector;" (capitalization is important)

then eventually you'll declare an instance
"Vector vecSomething = new Vector();"


then you start putting stuff into it using:
"vecSomething.addElement(objToStore);"
where objToStore is any object, and consequently, pretty much any kind of variable ... this adds new data to the end of the Vector, which will expand to accommodate the data

maybe you'll need direct access functionality, so you'd use "vecSomething.addElementAt(intYouWantAccessed, objToStore);" (remember that the 1st element is at index zero and not at index 1)

sooner or later, you'll want to remove stuff, so use "vecSomething.removeElementAt(intYouWantToAccess;"

there is also "vecSomething.removeAllElements();"

and most importantly you'll want to retrieve information stored in the array.. but since there's a trick to it, I included it last. The trick is that once you store something in a Vector it is casted to an Object class. So, you'll have to cast it back to whatever you had before. So, say you stored Strings in the Vector and you want to retrieve the first one. Do this.

String strRetrieve;
strRetrieve = (String)vecSomething.elementAt(0);

that pretty much covers what an API reference would ... so good luck

Mike (another Mike)


9-16-98

sorry .. correction to prev. reply

to insert an element at a specific index ... the method is

vecSomething.insertElementAt(Object, iIndex);

Mike


Home / Java Q & A Archive Page 1 / Java Q & A Archive / Java Q & A Main Page