473,406 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,406 developers and data experts.

Author Nomad: ArrayLists

11,448 Expert 8TB
What is an ArrayList

In Java, Arrays are used to store multiple items of the same time in an easy to
use structure. When you want to store multiple pieces of data and have data
types relate to each other (such as Employee name, address, hours that you can
use a set of parallel arrays or create an Employee class and use a single array
that holds the objects.

The problem with using Arrays is that you must set the size of the array when
it is created. For example:

Expand|Select|Wrap|Line Numbers
  1. Employee[] emparray = new Employee[10];
  2.  
This creates an array that can only hold 10 employee objects. If you try to
store more than 10 elements in this array, Java throws an error exception.
Having to initially set the size of such arrays is very limiting since you may
not know that you will have only at most (or exactly) 10 Employees.

One way to solve this problem is to use some of the built-in Data Structure
classes found in Java. The main purpose of such data structures is to make a
place you can store things like Employee objects that is not constrained by
size and that makes it easy to retrieve data from the data structure.

Java provides a data structure called an ArrayList. This works like a
combination of Linked List and Array in that you can store as much as you like
in this structure and it will grow accordingly. You can also access elements in
this structure by using an index value, much as you would with an Array.

There are some restrictions using ArrayLists is that they can only handle Class
objects and cannot easily handle basic data types such as integers and doubles.
If you want to store such information in an ArrayList you will have to first
convert it to object data types.

Java 1.4 and before wanted you to wrap ints into Integers, doubles into Doubles
etc.etc. This is what a fragment of Java 1.4 looked like:

Expand|Select|Wrap|Line Numbers
  1. List array= new ArrayList();
  2. for (int i= 0; i < 10; i++) {
  3.    array.add(new Integer(i));
  4.    int j= ((Integer)array.get(i)).intValue(); // get value back
  5.  
... and this is what the same sources look like in Java 1.5 or higher:

Expand|Select|Wrap|Line Numbers
  1. List<Integer> array= new ArrayList<Integer>();
  2. for (int i= 0; i < 10; i++) {
  3.    arrray.add(i);
  4.    int j= array.get(i); // get value back
  5.  
The second limitation of an ArrayList is that to use search features you must
add some special methods to your Classes. These methods are the equals(),
hashCode() and compareTo() methods. This will be explained later on..

Creating an ArrayList is done by importing the java.util.*; package or just the
single class itself: import java.util.ArrayList class and then creating an
instance of the ArrayList class:

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. ...
  3. List<PersonClass> arlist = new ArrayList<PersonClass>();
  4.  
Basically, what you do when you create an ArrayList object (in this case arlist)
is to use the name of the class that will be used to create the objects that
will be stored in the list. This class name is placed between a pair of < >
(<Employee> ) symbols and placed after the ArrayList class name both places it
is used when creating the arraylist object. In this case, the class that will
be used to create objects to be stored in this arraylist is the Employee class.

Using the Arraylist

Once an ArrayList is created, you can create the objects that will be added and
then add them to the list. This is done with the add() command:

Expand|Select|Wrap|Line Numbers
  1. PersonClass temp = new PersonClass ("NW123");
  2. arlist.add(temp);
  3.  
This command adds the object temp to the end of the list. If you wanted to add
it to a particular index position in the list you would use the command:

Expand|Select|Wrap|Line Numbers
  1. PersonClass temp = new PersonClass ("NW123");
  2. arlist.add(3, temp);
  3.  
This shifts all elements 'down' and places this new object at position 3.
If you wanted to replace the element at position 3 with the new object just
created, you would use:

Expand|Select|Wrap|Line Numbers
  1. PersonClass temp = new PersonClass ("E123");
  2. arlist.set(3, temp);
  3.  
If you wanted to remove the element 5 you would use:

Expand|Select|Wrap|Line Numbers
  1. arlist.remove(5);
  2.  
To get an object at position 5 you would use:

Expand|Select|Wrap|Line Numbers
  1. Employee x;
  2. x = arlist.get(5);
  3.  
To get the size of the ArrayList object and how many elements it is currently
holding) you would use:

Expand|Select|Wrap|Line Numbers
  1. int empsize = arlist.size();
  2.  
If you want to view the size you would use the:

Expand|Select|Wrap|Line Numbers
  1. System.out.println("The size is "+empsize () );
  2.  
To loop through a list and visit each element you can use the for() loop:

Expand|Select|Wrap|Line Numbers
  1. for(PersonClass e : arlist ) {
  2.    System.out.println("The name is "+e.getLname() );
  3. }
  4.  
The for() loop will go through all elements in the arraylist, in the same order
as an Iterator would do. Iterators iterate over a List starting at the first
element, ending at the last element; so the obove loop visits each element in
the same order as the loop below would do:

Expand|Select|Wrap|Line Numbers
  1. for( int i=0; i<arlist.size(); i++) {
  2.    PersonClass e = arlist.get( i );
  3.    System.out.println("The info is "+e.getEmpID(), +e.getLname() );
  4. }
Here the size() method on the ArrayList is used to mark the end of the loop.
The i variable is used as the ArrayList index and used with the get() method
to return the object. The PersonClass object e is only used to hold the
reference to the object in the list.

This completes this short introduction of the ArrayList class. There's another
List implementation: the LinkedList that behaves similar to the ArrayList.
Both type of lists have their pros and cons: an ArrayList is extremely fast
when you want to access elements given an index value. A LinkedList is very
fast when it comes to deletion or insertion of elements anywhere in the list.

Given the characteristics of your algorithm select the correct type of list.
Note that your algorithm itself should refer to the particular list as an object
of type 'List', i.e. just the interface type. This makes it very easy to select
another type of List when needed; just the construction part of the List would
know about what type of List will be actually constructed.

There are more datastructures available in the Collections framework; they are
the subject of other articles.
Jun 4 '07 #1
2 8460
need a class
which is same as ArrayList
and it's toString() should return size of arraylist
Mar 3 '08 #2
r035198x
13,262 8TB
need a class
which is same as ArrayList
and it's toString() should return size of arraylist
Just extend the normal ArrayList class and override it's toString method to return size().
Jun 19 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Brandon Potter | last post by:
Trying to find the best way to find common entries in an x number of ArrayLists or arrays of integers. Curious if there is a method already available in .NET to do just this very thing. ...
1
by: godsella | last post by:
First i have two stored procedures, i have passed the values of each one into two different arraylists of dates. how can i compare the two arraylists of dates? Thanks in advance
5
by: drdave | last post by:
I would like to have ten arraylists created within a loop.. is there a conversion or something I can do to acheive this.. pseudo: Dim counter As Integer = 0 Dim ArrName As ArrayList ...
0
by: steve | last post by:
I'm looking for a code example how to compare the values in a given record in different arraylists two arraylists, two fields in each record, both defined as string I'm thinking that it's...
3
by: steve | last post by:
I need to compare the value of a field in a row on an arraylist with the value of a field on a second arraylist I have this bit of code working for arrays but cant get it working for arraylists The...
4
by: Andy in S. Jersey | last post by:
I would like to create an unknown number of Arraylists, meaning, I don't know how many I should create until runtime. I will be reading a table, and 0,1,2, or more fields have to be put into...
2
by: Andy in S. Jersey | last post by:
I would like to create an unknown number of ArrayLists, that is I don't know that until runtime. Of course I can do this if I knew I needed two: ArrayList IntervalArray1 = new ArrayList();...
1
by: Newbie19 | last post by:
I'm just learning java arrays/arraylists and was wondering what are the best books for learning java arrays/arraylists? I know practice is the best way to learn, but I have a hard time...
3
by: =?Utf-8?B?Sm9zaFA=?= | last post by:
Hi All, I am attempting to compare values in two arraylists to make sure all the values are the same. I am running into trouble with my code if both arraylists compare okay up until a point and I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.