ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ECLIPSE IDE - Have a List of Items? Make use of the ArrayList JAVA Package

Updated on February 25, 2014

A "Teaser" From the Last Tutorial: One Key Automated Testing

In the wrap up of the last tutorial we ended performing a test for the relationship that was created between the Car class and the BillingAddress class which were related on the name company field. That tutorial was entitled:

ECLIPSE IDE JAVA Tutorial – Creating Relationships Between Classes

In closing, it was mentioned that it was possible to have all of the tests in a package run with one keystroke.

Here's how: Open your test package and you will see the tests created. Now, what you will be doing is creating a new test which includes all of your tests. Click on the test package name, then follow New> Other> JUnit > JUnit > JUnitTestSuite. The next display will show you a screen with a listing of all of the tests in the package. You can modify this list by selecting or deselecting tests. You can also change the name of the test suite to be created. When done, click on finish. That's it, it's that simple!

Now to run the test, select it from the updated list then it's merely a process of clicking on Run> JUnit Test. Looking at the source of the AllTests.java file, it's not really necessary to know about the annotations. If you create a new test, just added it to the list of tests.

The illustrations which follow detail the process.


Steps in Creating the JAVA Test Suite for an Application

The tests created in the package under the test folder.
The tests created in the package under the test folder.
Select JUnit Test Suite
Select JUnit Test Suite
The name of the test suit can be changed. Tests can be deselected or selected as desired.
The name of the test suit can be changed. Tests can be deselected or selected as desired.
The source of the test suite. Note items can be manually added to this file.
The source of the test suite. Note items can be manually added to this file.
Run the test suite. Note that one of the tests failed. This summary show the test is "not yet implemented".
Run the test suite. Note that one of the tests failed. This summary show the test is "not yet implemented".
Click on the failed test illustrates that it was set to fail, having not been implemented as yet.
Click on the failed test illustrates that it was set to fail, having not been implemented as yet.

The Main Objective of this Tutorial: Working with ArrayList()

To introduce the need for a generalized way of creating and manipulating lists of items. Let's consider the case of Chipmunk's Car Rental Agency. Currently we have defined two classes one that has details about cars and the other billing address information about the companies which are on the approved list of customers.

What Chipmunk doesn't know is how many cars he will eventually have if the agency grows and as word of mouth of the excellent service the agency provides, surely the BillingAddress list will grow as the agency grows. It would clearly be great if the application developed could hand any number of cars and customers.

JAVA has a number of classes available for just this situation. One of these class is called the array list, specified in code as ArrayList.

The array list allows for the creation of an array of any length. There is no need to worry about maximum values. The ArrayList is part of the java.util package. However one proceeds, importing this class is an essential operation.

In a previous tutorial, we learned that a good way to initially try out something is to sketch it out first using the scrapbook page. So to proceed, open the scrapbook page. If you do not remember how to get to the scrapbook page it is by go to File > New > Other > Java Run/Debug > Scrapbook page. It is always a good idea to create a new scrapbook page, particularly if you have several hot issues that you are working on at the same time.



Experimenting with ArrayList

The remainder of this tutorial will involve examples of important ArrayList features. We ill use the scrapbook page whose use was demonstrated in a previous tutorial.

To open the scrapbook page, select New> Other> Scrapbook Page. We will enter code here and create an ending expression line, and click on the magnifying glass icon to inspect our results.

Import the Packages Needed for the Example

Once in the scrapbook page, perform either of the two following procedures:

import java.util,*;

import org.getterandsetter.tutorial.*

or we can just use the icon for “Setting the Import Package for Running Code”, which is at the far right of the of the list of icons in the icon toolbar. Once we begin typing, ECLIPSE will present a list of suggestions.

Importing packages saves us the typing of the fully qualified name of a class. For example, the array list would have to be specified as java.util.ArrayList rather than as its short name ArrayList.

Importing the Packages

The list of packages available for importing.
The list of packages available for importing.
The two packages we need to import in orderto specify the "short" class names.
The two packages we need to import in orderto specify the "short" class names.

Creating an ArrayList with a New Shorthand Method

ECLIPSE has a lot of ways of helping a developer perform common functions whithout having to give it much thought.

Here's a new one. We want to create an object of class ArrayList. Now especially for new Java developer, one has to think of the syntax until it becomes second nature. Here's one way of create a new object. Type new followed by the combination CNTL-space bar. A popup will appear. Now select new - create new object. ECLIPSE will add a new line to your program which is prefilled will type, name, argument sub-fields defined, and the require word new. Then all one has to do is change the type, select a name for the object, and specify arguments (if required). The snapshots which follow illustrate this for creating an ArrayList object.



Creating An ArrayList Object Using a Shorthand

Type new followed by CNTL (control key) and space (pressing the space bar. This bring up the selection.Select create new object.
Type new followed by CNTL (control key) and space (pressing the space bar. This bring up the selection.Select create new object.
A template for a new object statement is created.
A template for a new object statement is created.
Fill in the statement fields. type is ArrayList. We used list for the name.
Fill in the statement fields. type is ArrayList. We used list for the name.

Creating an ArrayList with a New Shorthand Method

The array list is created by typing the word

new

Now the new trick is to type CNTL followed by a space and when the popup wind is presented select create a new object.

What appear is as follows:

type name = new type(arguments);

replace the text with

ArrayList<String> list = new <String>ArrayList();

The text "<String>" is one we have not seen before. What is it? It is referred to as a generic. What it means in practice is that we select a type for an object and if we add an item to the object which does not conform to the object type, a compiler error is thrown. This will make more sense as we work out the following example.


Adding to An Array List

What good is an array list? Well, that's pretty simple. In Chipmunk's Car Rental Agency he has two classes: the car class and the billing address class. He will want to add cars and customers to his lists as he acquires them.

If we type the object name, list, followed by a period, ECLIPSE will present a list of methods associated with the ArrayList class. One of these is the method add.

The following shapshots illustrate. adding two entries to our list and then displaying them by means of the inspecting them (using the magnifying glass.

Adding to the Array

The code for this example.
The code for this example.
Inspecting the array entries. Note the array index  starts at 0.
Inspecting the array entries. Note the array index starts at 0.
Expanding the first entry. Notice that the model has been updated. The other fields are set via the constructor.
Expanding the first entry. Notice that the model has been updated. The other fields are set via the constructor.

Revisiting the Generic

The "<String>" notation and what a generic does should become apparent when we run the following example in subsequent snapshot. We have added a statement for an integer field to be added to the array:

list.add(99);

this is invalid since we specified that the array would consist of strings. ECLIPSE detect the error at compile time. This helps avoid costly, often hard to find runtime errors.



Three More ArrayList Methods: get(), indexOf(), and remove()

We will conclude this tutorial with three more method:

  • remove() - if we add an array entry to our lest, this gives us a way of removing it.
  • get() - we can get a array entry by using index into it. Remember the first element of the array is identified by 0, the second by 1, an so forth.
  • indexOf() - if we know the object, we can obtain its index number

The last two are a little more interesting than the first. Remember, if we know the index we can obtain the object and if we know the object we can acquire its. index.

Wrap Up and What's Next

In this tutorial utilizing the scrapbook page feature of ECLIPSE we created a number of examples experimenting with the ArrayList() class. We looked at the method add in some detail and defined three more methods (get, indexOf, and remove).

Several new shorthand tricks or aids were demonstrated: creating a new object from a template and creating a fully automated, single key testing mechanism by creating a test suite.

We learned a new coding feature, the generic feature. This feature detect errors at compile time for mismatched types rather than at runtime where errors can be much more difficult to track down.

In the next tutorial we will get back to our Chipmunk's Car Rental Agency where we will be involved in creating and manipulating lists.

How Are We Doing? Do These Tutorials Meet Your Needs?

Cast your vote for Please rate the contents of this tutorial. Thanks!
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)