my dog learned polymorphism*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "size()" Watch "size()" New topic
Author

size()

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.
Thanks.
Darrin Cartwright
Ranch Hand

Joined: Dec 27, 2002
Posts: 107
Howdy!
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:
i.e.:
int [] myArray = {1,2,3};
int size = myArray.length;
System.out.println("Array length: " + size);
This would produce: Array length: 3
Enjoy,
Darrin


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

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
HTH
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: size()
 
Similar Threads
JPQL Query Dout
Difference Between count() and size
setting a jsp variable to a returned value of a javascript function??
size() collection not working in HQL
Hash Tables