Array lists
This presentation is the property of its rightful owner.
Sponsored Links
1 / 8

Array Lists PowerPoint PPT Presentation


  • 54 Views
  • Uploaded on
  • Presentation posted in: General

Array Lists. Arrays in Java. Can set size at run time (as in C++) int actualSize = …; Emp [ ] staff = new Emp [actualSize]; Does not completely resolve problem of dynamically modifying arrays – once array size is set, cannot change easily. ArrayList class in Java.

Download Presentation

Array Lists

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Array lists

Array Lists


Arrays in java

Arrays in Java

  • Can set size at run time (as in C++)

    int actualSize = …;

    Emp [ ] staff = new Emp [actualSize];

  • Does not completely resolve problem of dynamically modifying arrays – once array size is set, cannot change easily.


Arraylist class in java

ArrayList class in Java

  • It is a library class defined in java.util package

  • Array that will shrink and grow dynamically

  • Lower bound is 0

  • Holds elements of type Object so you’ll need to cast whenever you take an item out of an array list


Add method

add Method

ArrayList staff = new ArrayList( );

staff.add (new Emp ( …) );

staff.add (new Emp (…) );

  • ArrayList class manages internal array of Object references.

  • When it gets full, then the array list automatically creates a bigger array and copies objects in smaller array to bigger array.


Size method

size Method

  • Returns actual number of elements in array list

    staff.size ( );

  • When you know it has reached permanent size

    staff.trimToSize ( );


Accessing array list elements

Accessing Array List elements

  • Nothing is free

  • To set ith element: staff.set (i, harry);

  • To get ith element (Object), must cast

    employee e = (Emp) staff.get( i);


Arraylist trick

ArrayList Trick

  • Flexible growth and convenient element access

  • First make an array list and add elements

    ArrayList list = new ArrayList ( );

    while ( …)

    {

    x = …;

    list.add (x);

    }

  • Then use toArray method to copy elements into array.


Arraylist trick1

ArrayList Trick

  • Then use toArray method to copy elements into array.

    X [ ] a = new X [list.size ( ) ];

    list.toArray (a);

  • I used this in my solution to Program 2 because you don’t know how many items there are until you’ve finished reading them all !!!


  • Login