how is size of an array determined?
Printable View
how is size of an array determined?
Assuming that you have an array declared, you can use the length parameter to discern it's length.
If you are asking how you set the size of an array, that is totally up to the user.
Example:
int[] array1 = new int[10];// Makes a new character array with a length of 10, which will be 0-9 since arrays are 0-indexed.
for (int i=0; i < array1.length; i++){
System.out.println("Hello World");
}
or you could iterate over the array in this way:
Type would be what ever the type array you have. String Array would be like so:Code:for(type t : arrayName){
System.out.println(t);
}
So the Sysout would print the place of arrayName[0-...];Code:for(String t : arrayName){
System.out.println(t);
}
sarevok9 answers this question though i would like to draw your attention to arraylists that increase and decrease in size automatically as elements are added to them; note the below example:
ArrayList <Integer> name = new ArrayList<Integer>();
to add to an arraylist: name.add(index,added value) or name.add(added value)
arrays lists can be created for strings and any other type of primitive using the wrapper classes of the primitive types (for example Integer instead of int for arrays)
to find the size of an arraylist: name.size();
make sure to include at the beginning of the code-import.java.util.*;-
Not my topic, but I would like to as you a question Farahm-
Why are you putting the 'Integer' in <'s and >'s? Does this have something to do with the constructor? I left my java book at home and I'm in my college right now.
Yes it is required while declaring an arraylist.
To elaborate on what they said, the generics specifies the type the arraylist(or other collection) contains. If you say Integer it let's you add integers to the array list.
In an array you do
If you dont specify a type it fills it with objects. The generic parameters make it so the object is cast to the correct type. Check out the oracle generics tutorials for more thorough explanations.Code:
Type[] varName
In a collection you do
Collection<Type> varName
Generic declarations are not required, but they do allow the compiler to check your code more thoroughly, and if you don't use them, you'll get a warning - which some find disturbing ;)