Simple Java ArrayList Example

  1. /*
  2.   Simple Java ArrayList Example
  3.   This Java Example shows how to create an object of Java ArrayList. It also
  4.   shows how to add elements to ArrayList and how get the same from ArrayList.
  5. */
  6.  
  7. import java.util.ArrayList;
  8.  
  9. public class SimpleArrayListExample {
  10.  
  11. public static void main(String[] args) {
  12.  
  13. //create an ArrayList object
  14. ArrayList arrayList = new ArrayList();
  15.  
  16. /*
  17.   Add elements to Arraylist using
  18.   boolean add(Object o) method. It returns true as a general behavior
  19.   of Collection.add method. The specified object is appended at the end
  20.   of the ArrayList.
  21.   */
  22. arrayList.add("1");
  23. arrayList.add("2");
  24. arrayList.add("3");
  25.  
  26. /*
  27.   Use get method of Java ArrayList class to display elements of ArrayList.
  28.   Object get(int index) returns and element at the specified index in
  29.   the ArrayList
  30.   */
  31. System.out.println("Getting elements of ArrayList");
  32. System.out.println(arrayList.get(0));
  33. System.out.println(arrayList.get(1));
  34. System.out.println(arrayList.get(2));
  35. }
  36. }
  37.  
  38. /*
  39. Output would be
  40. Getting elements of ArrayList
  41. 1
  42. 2
  43. 3
  44. */

Post new comment

To combat spam, please enter the code in the image.


Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!