• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

size()

 
Kevin Knowles
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jason Menard
Sheriff
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic