File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes size() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "size()" Watch "size()" New topic


Kevin Knowles
Ranch Hand

Joined: Dec 29, 2002
Posts: 45
I can't seem to find much instruction on the use of the size() function. I thought that it's use would be similar to the way it is used in C++, that is to get the size of an array. Can someone explain how the size() function is used in Java and perhaps provide me with some examples.
Darrin Cartwright
Ranch Hand

Joined: Dec 27, 2002
Posts: 107
It really depends on the class you are using when you call the size() method. If you are just wanting the length of an array you can use the name of the array to access its length:
int [] myArray = {1,2,3};
int size = myArray.length;
System.out.println("Array length: " + size);
This would produce: Array length: 3

Life is good on the Ponderosa,<br />but mind where you step.
Jason Menard

Joined: Nov 09, 2000
Posts: 6450
The size() method is most often seen as a method of the Collection interface and classes that implement it (Map, List, etc...). The size() method simply returns the number of elements in a collection. If you have an array of objects or primitives, you will use the length attribute for the same purpose.
ArrayList al = new ArrayList();
al.add("Hello World");
System.out.println("Number of elements in list: " + al.size();
This code would display:
Number of elements in list: 1
int[] x = {5, 10, 15, 20};
System.out.println("Number of elements in array: " + x.length;
This code displays:
Number of elements in array: 4
I agree. Here's the link:
subject: size()
It's not a secret anymore!