How can I get the size of an array, a Collection, or a String in Java?
Abridged:
For an array: use .length
.
For a Collection
(or Map
): use .size()
.
For a CharSequence
(which includes CharBuffer
, Segment
, String
, StringBuffer
, and StringBuilder
): use .length()
.
Arrays
One would use the .length
property on an array to access it. Despite an array being a dynamically created Object
, the mandate for the length
property is defined by the Java Language Specification, §10.3:
An array is created by an array creation expression (§15.10) or an
array initializer (§10.6).An array creation expression specifies the element type, the number of
levels of nested arrays, and the length of the array for at least one
of the levels of nesting. The array's length is available as a final
instance variablelength
.An array initializer creates an array and provides initial values for
all its components.
Since the length of an array cannot change without the creation of a new array instance, repeated accesses of .length
will not change the value, regardless of what is done to the array instance (unless its reference is replaced with a differently sized array).
As an example, to get the length of a declared one-dimensional array, one would write this:
double[] testScores = new double[] {100.0, 97.3, 88.3, 79.9};
System.out.println(testScores.length); // prints 4
To get lengths in an n-dimensional array, one needs to bear in mind that they are accessing one dimension of the array at a time.
Here's an example for a two-dimensional array.
int[][] matrix
= new int[][] {
{1, 2, 3, 4},
{-1, 2, -3, 4},
{1, -2, 3, -4}
};
System.out.println(matrix.length); // prints 3 (row length or the length of the array that holds the other arrays)
System.out.println(matrix[0].length); // prints 4 (column length or the length of the array at the index 0)
This is important to make use of, especially in the case of jagged arrays; the columns or rows may not always line up all the time.
Collections (Set
, List
, etc.)
For every object that implements the Collection
interface, they will have a method called size()
with which to access the overall size of the collection.
Unlike arrays, collections are not fixed length, and can have elements added or removed at any time. A call to size()
will produce a nonzero result if and only if there has been anything added to the list itself.
Example:
List<String> shoppingList = new ArrayList<>();
shoppingList.add("Eggs");
System.out.println(shoppingList.size()); // prints 1
Certain collections may refuse to add an element, either because it's null
, or it's a duplicate (in the case of a Set
). In this case, repeated additions to the collection will not cause the size to increment.
Example:
Set<String> uniqueShoppingList = new HashSet<>();
uniqueShoppingList.add("Milk");
System.out.println(uniqueShoppingList.size()); // prints 1
uniqueShoppingList.add("Milk");
System.out.println(uniqueShoppingList.size()); // prints 1
Accessing the size of a List<List<Object>>
* is done in a similar way to a jagged array:
List<List<Integer>> oddCollection = new ArrayList<>();
List<Integer> numbers = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
}};
oddCollection.add(numbers);
System.out.println(oddCollection.size()); // prints 1
System.out.println(oddCollection.get(0).size()); // prints 3
*: Collection
doesn't have the get
method defined in its interface.
As an aside, a Map
is not a Collection
, but it also has a size()
method defined. This simply returns the number of key-value pairs contained in the Map
.
String
A String
has a method length()
defined. What it does is print the number of characters present in that instance of the String
.
Example:
System.out.println("alphabet".length()); // prints 8
Java String array: is there a size of method?
Yes, .length
(property-like, not a method):
String[] array = new String[10];
int size = array.length;
How to find length of a string array?
Since car
has not been initialized, it has no length, its value is null
. However, the compiler won't even allow you to compile that code as is, throwing the following error: variable car might not have been initialized.
You need to initialize it first, and then you can use .length
:
String car[] = new String[] { "BMW", "Bentley" };
System.out.println(car.length);
If you need to initialize an empty array, you can use the following:
String car[] = new String[] { }; // or simply String car[] = { };
System.out.println(car.length);
If you need to initialize it with a specific size, in order to fill certain positions, you can use the following:
String car[] = new String[3]; // initialize a String[] with length 3
System.out.println(car.length); // 3
car[0] = "BMW";
System.out.println(car.length); // 3
However, I'd recommend that you use a List
instead, if you intend to add elements to it:
List<String> cars = new ArrayList<String>();
System.out.println(cars.size()); // 0
cars.add("BMW");
System.out.println(cars.size()); // 1
Java is there a way to get the size of an array without knowing the type?
Yes. Use Array.getLength()
Object x; // assuming it’s an array
int length = Array.getLength(x);
How do you determine size of string array java?
Use the length
property of the array:
int numArrayElements = tokens.length;
How can I get the size of a string array?
If you want the amount of elements in this array String[] array = s.split(",");
just do:
array.length
To convert this array to a list do this:
public ArrayList<String> myList = new ArrayList<String>();
String[] array = s.split(",");
myList = Arrays.asList(array);
Related Topics
Does a Tcp Socket Connection Have a "Keep Alive"
How to Find Nth Occurrence of Character in a String
Why Do I Get the "Unhandled Exception Type Ioexception"
Is There a Good Natural Language Processing Library
Why Does the Jvm Still Not Support Tail-Call Optimization
Swingutilities.Invokelater() Why Is It Needed
Difference Between Spring @Controller and @Restcontroller Annotation
Spring: How to Inject an Httpservletrequest into a Request-Scoped Bean
Surefire Is Not Picking Up Junit 5 Tests
List Versus Arraylist as Reference Type
How to Implement a Db Listener in Java
Send an Array with an Http Get
Why to Use Swingutilities.Invokelater in Main Method
How to Go About Formatting 1200 to 1.2K in Java
How to Remove Special Characters from a String
How to Use "." as the Delimiter with String.Split() in Java
In Java, How to Check If a String Contains a Substring (Ignoring Case)