This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by Candy Bortniker: Ok, I was reading through here to see if I could offer advice or more likely learn something, then I got confused. I thought that arrays could be only int or float, etc. I just learned about vectors, similar to arrays but they hold objects such as strings. Am I misunderstanding something?
In Java, you can make an array of any data type. So, you can have int, float, String, Applet, Object, etc. You can put ints into an int array, floats into a float array, Strings into a String array, Objects into an Object array. In simple terms, Vector is a collection class that provides a user friendly interface to an Object array (Object). The underlying data structure of a Vector is an Object array. So, into a Vector can be put any Object. Take a look at The Collections Trail of Sun's Java Tutorial for more information on collection data structures such as Vector. And you might want to take a peek at a convesation begun by Chris Stewart over in the Intermediate Forum. Does that help?
Please Candy, don't gush like that. You're going to embarass Dirk. I just wanted to add that even other arrays can be stored in arrays, although it's generally easier to think of the result as a two-dimensional array.
Is there a way to do a dynamic primitive array? IE not having to declare the size when declaring the array. something where i can populate it on the fly, like: myArray [myArray.length] = something1; myArray [myArray.length] = something2; myArray [myArray.length] = something3; myArray [myArray.length] = something4; etc. etc. Basically, i'm just lazy
Joined: Dec 10, 2001
When you declare an array, you must provide an int to specify the size. The actual value of that int doesn't have to be known at compile time. So, it could be the result of some equation or the return value of some method. Note that myArray[myArray.length] would always cause an ArrayIndexOutOfBoundsException as array indexes start at 0 and the last component is at index myArray.length-1 (nevermind zero-length arrays). [ March 20, 2003: Message edited by: Dirk Schreckmann ]
If you're just lazy, try to do creative things with cut-and-paste. If you actually can't tell how many elements the array will eventually need to store, use a Vector or ArrayList, which are like growable arrays. They don't work with primitives, but you can use the wrapper classes: Integer, Double, etc., to make up for that.