ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ECLIPSE IDE Tutorials - Creating add() and remove() Methods For Objects in Lists

Updated on February 27, 2014

In the Preceding Tutorial.......

In the preceding tutorial, "ECLIPSE IDE Tutorial - Creating A Resource Class Composed of Object Lists", the constructor class was created for the two list resources we will be relying on in our car rental agency example. We created two new lists, the car list and the billing address list. Our test method assertTrue() introduced a method which returns a value of true or false using the instanceof operator.

Sever tips were added as to how ECLIPSE helps in the development process through the use of color and editor window flags.

A short discussion of the differences between JUnit 3 and JUnit 4 was also included.


Focus of ThisTutorial

This tutorial will focus on the creation of two basic methods which will allow the addition and removal of items from the lists. Test cases will be created. The benefit of Java generic coding will be demonstrated.

Automatically Generating "getter" Method

Starting from the source ("src'" folder) we will want to have methods avaialble for getting objects. ECLIPSE as you are aware of at this point has an automatic way of generating these methods. Starting from the toolbar select Source>Generate Getters and Setters... . For our purposes we do not need the "setter" method, we just need the "getter" methods.The chck boxes are clicked for name, BillingAddress, and Car. Once selected we click OK and the "stub code for these methods is added to our resource source file as illustrated in the snapshots which follow.

Selecting the "getter" Methods and the Resulting Code

The "setter" methods are selected for creation.
The "setter" methods are selected for creation.
The code gererated by ECLIPSE is included in our resources file.
The code gererated by ECLIPSE is included in our resources file.

An ECLIPSE Helpful Hint

When code changes are made (even when those code changes are suggested by ECLIPSE) is it always a good idea to test the new code. At the conclusion of the last tutorial our test case with the new constructor added ran successfully. Running the test case after the generation of the "getters" is a good idea.

Adding a Method to Populate the LIists

In order to test the add and remove methods, the lists should have some list items in it. To avoid code duplication later on we will add a new methods. We will need some cars and billing addresses defined as well as an object which identifies our resources.

In this example we create a method called populateArrays() to add these objects.

First, we create two car objects:

Car c1 = new Car("Ford F150");

Car c2 = new Car("Mercedes Benz");

and two billing address objects:

BillingAddess ba1= new BillingAddress();

BillingAddess ba2 = new BillingAddress();

Since BillingAddress was created without arguments we need to set values for the company name field:

ba1.setCompanyName("Starbucks");

ba2.setCompanyName("Lowe's SuperSave");

and to indicate that these are test resources we add giving the object the name :

CarRentalResources crr1 = new CarRentalResources("Test");

In the following, the use of color indicates that we have a problem. The black text indicates that the fields created have been created as local fields. ECLIPSE has a way of correcting this which we will see next.

Oh no! A Problem the Fields Are Local Variables

Correcting the Problem Using JAVA Code Refactoring

In the tutorials presented thus far we have not had an occasion to touch on the subject of "refactoring". Not only that but this may seem like a strange word which even experienced developers may not have encountered.

So what is refactoring?

Refactoring is a method of restructuring computer code, changing the factoring, to make it more usable or extensible.". One of the types of code refoactoring which we will next demonstrate is to create a more generalized type, to allow for greater code sharing. Which seems to be our need. For the defined fields to be useful they must be available to other methods in the class.

How do we do this?

Highlight the statements referring to a car. Select Refactor from the tool bar and follow with option Convert Local Variable to Field. A popup window appears with a number of options. Choose the radio buttom for public, then click on OK. When the source window is refreshed you see the code has changed. Now repeat the process for the other car object which was created as well as the two BillingAddress objects and the resource.

Did anything else change in the code?

Yes, declarations were added for each of the variables which have now been included as field definitions accessible to the class methods.

The following snapshots highlight the process and results.

JAVA Refactoring of the Local Fields

After highlighting a statement in the code. Choose Refactor from the toolbar. Select the option to "Convert Local Variable to Field". This popup appears.
After highlighting a statement in the code. Choose Refactor from the toolbar. Select the option to "Convert Local Variable to Field". This popup appears.
Note after refactoring, the code is changed.
Note after refactoring, the code is changed.
Note also that field definitions have been added. This allow other methods to access them. Refactoring has generalized the type.
Note also that field definitions have been added. This allow other methods to access them. Refactoring has generalized the type.

Creating the Test Method

Now we start creating the four test methods: addCar(), removeCar(), addBillingAddress(), and removeBillingAddress()

Start with the addCar() method. with the access method of public:

public void addCar();

Next we call the method to initialize our list with the call to populateArrays()method.

populateArrays();

We then test that the number of objects in the car list is zero:

// test that we started from an empty array

assertEquals(0, getCar().size());

We add the cars to the list using the not as yet created addCar() method.

// add cars to the list

crr1.addCar(c1);

crr1.addCar(c2);

Next we add assert methods to check that the size of the list correctly reflects the added cars:

assertEquals(2,crr1.getCar().size());

We check the correctness of the index of each of the cars. Note that lists are indexed starting at 0 and not 1.

assertEquals(0,getCar().indexOf(c1));

assertEquals(1,getCar().indexOf(c2));

Now we test (our yet to be created removeCar() method).

removeCar(c1);

Now check the array list size with the assert statement.

assertEquals(1,crr1.getCar().size());

We check that the index of what was the second car, which has now become the only (and first) car in the list should now be 0.

assertEquals(0,getCar().indexOf(c2));

We remove the remaining car in the list and check that the size of the list is 0:.

crr1.removeCar(c2);

assertEquals(0,crr1.getCar().size());

We use ECLIPSE “quick fix” to add both the addCar()and removeCar to source resource program.

Now in our source we write the two methods. They are both rather simple, since we are using built-in methods from the array class.

In the addCar() method we add the statement:

this.car.add(c1);

and in the removeCar() method we add the statement:

this.car.remove(c1).

Remember the use of the word this, it is a reference to the current object.

The billing address list is treated in a similar way. The code can be copied from the add methods replacing "car" with "billingAddress", "Car " with "car ", and change the prefixes of "c" with "ba" for the fields. The code for the calling methods and test methods appear in the shapshots below.


The Coded Methods for this Tutorial

The addCar() Test Method, actually does both  first adds and then removes the cars.
The addCar() Test Method, actually does both first adds and then removes the cars.
The addBillingAddress() Method mirrors the actions of  the addCar() Method. It acts upon billing addresses.
The addBillingAddress() Method mirrors the actions of the addCar() Method. It acts upon billing addresses.
The four methods which invoke the test cases.
The four methods which invoke the test cases.

A Final Step, Run the Test

Finally, if all has gone well, the JUnit test should pass. If you have problems or issues please send a comment and I'll try to help.

A Recap of the Tutorial and What's Next

In this tutorial we created the methods to manipulate lists in JAVA. Appropriate test cases were added.

The assertTrue() method was introduced. This is a Boolean method which evaluates to true or false. The operator used in this method is the instanceof which compares the type of an object with the class type.

The term refractor was introduced. Refactor has a number of uses. In our example we used to to generalize fields, transforming them from local variables to class fields.

Finally, we used previous hints about color and statement hints to avoid a problem and suggested that frequent saving and testing of code changes is really essential. The hint about using "quick fix" for repetitive error corrections may seem an overkill but it can prevent coding errors and typos.

In the next tutorial we will create a number of methods:

checkoutCar(), checkinCar() - cars are rented and returned. Methods to associate a car with a company rental must be kept up to date.

getAvailableCars(),- we must know what cars are available for rental. Having a handy list let's both the rental agency and the potential customer know what their options are.

getUnavalibleCars(),- cars may be unavailable for reasons other than their rental (e.g. repair, servicing)

getCarsForBillingAddress() - for the billing department (and other uses) there is a need to know what cars are rented to what company.

Well that's all!


How are we doing?

Cast your vote for How clear, concise, and useful was this tutorial?
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)