Linked Lists in Java



Linked Lists, Iterators and Programs

Contents:

Part 0: Things to know before you study Part 1

Part 1: Introduction to iterators

Part 2: Introduction to the code for iterators

Part 3: More about Removal of an element from a linked list

Part 4: Addition of an element to a linked list

Part 5: Storing data of any type in a linked list

Part 6: Using your own classes with Java’s collection classes

Part 7: Defining an equals method

Part 8: A complete set of software to illustrate the above discussion

Part 9: The software above repeated with the facility to search for a

Rectangle of the user’s choice

Part 10: Menu-driven list processing software 1

Part 11: Menu-driven list processing software 2

Part 12: Menu-driven list processing software 3

Part 0: Things to know before you study Part 1

1. ITERATOR

An iterator is an object that allows a programmer to traverse through all the elements of a collection, such as a linked list or an array list. What is meant by this will be abundantly clear in the notes that follow.

2. COMPARE TO

You can send messages to string objects to make them tell you if they’re alphabetically before or alphabetically after other strings.

pareTo(s2)

means we’re sending a message to String variable s1 asking it whether the string it contains is alphabetically before or after what’s contained in String variable s2.

If it’s before it sends back a number less than 0.

If it’s after it sends back a number greater than 0.

If it’s equal it sends back 0.

Here’s an example of its use:

if(pareTo(s2) < 0)

System.out.println(s1 + “is before “ + s2 “in the alphabet”);

This would be the case, if for instance s1 contained apple and s2 contained apricot.

3. EQUALS:

We can send a message to String variable s1 asking if what’s in it is equal to what’s in String variable s2.

s1.equals(s2)

means we’re sending a message to s1 asking if its contents is equal to s2’s contents. It sends back the boolean value true if so, and false if not.

Here’s an example of its use:

if(s1.equals(s2))

System.out.println(“Your two strings are equal”);

This would be the case if, say, both s1 and s2 contained the string apple.

Here’s another:

if(!s1.equals(s2))

System.out.println(“Your two strings aren’t equal”);

As you know the brackets after an if expects to find a boolean expression inside itself.

Given that equals returns a boolean, this need is provided for.

Self assessment test:

1. What’s the return type of compareTo?

2. What’s the return type of equals?

3. If we couldn’t send equals messages to strings, we could use compareTo as a substitute. Show how this is possible by rewriting the relevant part of the second example below.

Exercise: Write a program to ask the user for two strings and to report whether the first comes before the second in the alphabet, after the second in the alphabet or is equal to the second string. Allow the program to ask the user for successive sets of input until the user has had enough.

Part 1: Introduction to iterators

Do you know what the cursor is in a word processor, or a text editor? It’s an imaginary pointer says where insertion or deletion will take place in the text. You can move the cursor along by the use of the arrow keys on the keyboard. Whenever a letter is inserted, it’s inserted at the position of the cursor and whenever a character is removed it’s removed just before where the cursor is. (Play around with Microsoft Word or any other editor or word processor and you’ll soon see what I mean.)

In the code below, we introduce a new class a ListIterator. It provides a cursor into any list that gets a listIterator message sent to it, using the usual notation:

objectName.messageName()

where objectName is the object to which the message called messageName is sent asking it to do something.

In this case you’ll see a line in the program below, highlighted in blue:

ListIterator iterator = staff.listIterator();

where staff is a LinkedList. This creates the cursor to navigate through the list.

Part 2: Introduction to the code for iterators

import java.util.LinkedList;

import java.util.ListIterator;

public class ListTester

{

public static void main(String [] args)

{

List staff = new LinkedList();

// The above construction is more or less like the ones we’ve seen before for

// Rectangles and so on in Server Scripting. There’s one small difference:

// the angle brackets and what they contain.

// We must decide what sort of objects our list will consist of. Here we’ve decided

// our linked list will be one of Strings, each of one letter representing the first letter

// in the first name of a number of members of staff in an organisation.

staff.add("F"); // for Fidelma

staff.add("B"); // for Bernard

staff.add("Z"); // for Zacahiah

staff.add("L"); // for Larry

// To help you follow what’s going on now write

// F B Z L

// on paper,

// with plenty of space between letters as shown here. Follow the logic below on

// your sheet of paper using say a I for the cursor that we’re about to create.

// Creating the cursor (or iterator):

// Next we send a listIterator message to staff and it returns a cursor to itself

// in ListIterator format. We’ve called this cursor iterator but we could have called

// it anything we liked. Would you have preferred to call it, say, cursor, or pointer?

// If so, use either of these names in your own software.

ListIterator iterator = staff.listIterator();

// cursor at its originating position, that is before F

iterator.next(); // asks the iterator to move along to the right

// to point betwewen the next pair of list members.

// It’s worth noting, incidentally, that there’s also a previous() message

// that can be sent.

// It moves the cursor back one space. We’ll use it later.

// as a result of the last message the cursor is after F

iterator.next();

// as a result of the last message the cursor is after B

iterator.add("N");

// N gets put into the list after B, i.e. at the position of the cursor;

// exactly as in a Word processor such as MS Word

iterator.add("P");

// P gets put into the list after N

iterator.next();

// cursor now after Z

iterator.remove();

// due to the last message the element before the cursor is now removed, i.e. Z

// Do you see that this is just like the backspace key in a word processor?

// now we print out the changed list, using a piece of syntax you may not have seen

// before, but is based on the for construct.

for(String name : staff)

System.out.println(name);

}

}

output:

F

B

N

P

L

We conclude, from all those details, that sending an add message to a list iterator object causes an element to be put in the list that the iterator refers to at the position of the cursor and then the cursor moves along beyond that newly inserted character.

We conclude, from all those details, that sending a remove message to a list iterator causes the element in the referred list before the cursor to be removed.

Part 3: More about Removal of an element from a linked list

This example shows a list being build of the letters A, B, C, D, E, and F. Then the human user is invited to type in one of these letters. The user’s choice of letter will

be removed before the list is printed out.

The way in which the removal is achieved is that a sequential search through the list

is made until a match is found. (A sequential search is one where the first element is tested first and then the second and then the third, one at a time.) See the while loop in the code below.

import java.util.LinkedList;

import java.util.ListIterator;

public class ListTesterRemove

{

public static void main(String [] args)

{

LinkedList staff = new LinkedList();

staff.add("A"); // the add message that is sent to lists…

staff.add("B"); // … not to be confused with the add…

staff.add("C"); // …message sent to iterator objects.

staff.add("D");

staff.add("E");

staff.add("F"); // now our list as A, B, C, D, E and F in it.

ListIterator iterator = staff.listIterator();

System.out.println("Please type one of the following letters, A,B, C, D, E or F ");

System.out.println("and it will be removed from the list. ");

// get the uer’s choice of single letter string to be removed

String s = Keyboard.readString();

System.out.println();

while(!iterator.next().equals(s)) // look for the position of the element to be removed

; // empty loop

// alternatively the two lines above can be replaced the the four lines below.

// String temp;

// temp = iterator.next();

// while(!temp.equals(s))

// temp = iterator.next();

// Now that we’ve found the correct position, send a remove message

// to remove the required list member:

iterator.remove();

/ / now we print out the changed list

for(String name : staff)

System.out.println(name);

}

}

The most complicated part of the program above is the part drawn in purple. Let’s look at it in some detail:

!iterator.next().equals(s)

First of all remember (see Part 0 above) that we can send an equals message to strings and they respond with true or false according to whether or not they’re equal to the string that is sent along with the message.

Here’s an exert from part 0:

s1.equals(s2)

means we’re sending a message to s1 asking if it’s equal to s2. It sends back the boolean value true if so, and false if not.

In this case:

!iterator.next().equals(s)

we’re asking a string whether it’s equal to s the string the user typed in. The string we’re sending the messasge to is, of course, given by iterator.next() which is simply the next string that the iterator is indicating. Finally there’s the ! to consider. That makes the whole phrase read

while(not yet found a match to the string the user provides, keep going on through the list)

Part 4: Addition of an element to a linked list

This example shows a list being built from a number of foods. Then the human user is invited to type in another food. The user’s choice of food will be added to the list and then it is printed out.

The way in which the addition is achieved is that a sequential search through the list

is made until the correct alphabetical position is found. Then the new element is inserted. See the while loop in the code below.

import java.util.LinkedList;

import java.util.ListIterator;

public class ListTesterAdd

{

public static void main(String [] args)

{

LinkedList edibles = new LinkedList();

edibles.add("apple");

edibles.add("banana");

edibles.add("cabbage");

edibles.add("drinking-chocolate");

edibles.add("eggs");

ListIterator iterator = edibles.listIterator();

System.out.println(“Please type in a food item to be added to a list.\n ”):

System.out.println(“suggestions: croutons, dough, alfalfa.”);

String s = Keyboard.readString();

System.out.println();

// send a next message to iterator and then send a compareTo

// message to the result of that. Check out compareTo in

// part 0.

while(iterator.next().compareTo(s) < 0)

; // empty loop once more

//Oops! gone one too far along so backtrack one position!

iterator.previous();

// now add our new item at the correct position.

iterator.add(s);

// print out the list to see if it worked.

for(String name : edibles)

System.out.println(name);

}

}

The most difficult part of the above program is probably:

iterator.next().compareTo(s) < 0

All we’re saying there is while the next thing in the list is alphabetically before the thing the user wants to insert, keep going. It’s as simple as that really.

Part 5: Storing data of any type in a linked list

A linked list doesn’t have to contain just Strings. Far from it! It can store data of any class type

Thus we could have something like:

LinkedList staff = new LinkedList ();

Person mary = new Person();

mary.setName(“Mary Browne”);

mary.setAge(21);

Person john = new Person();

john.setName(“John Doyle”);

john.setAge(24);

staff.add(mary);

staff.addl(john);



}

Of course the above code assumes the existence of a Person class with member methods to support the sending of the messages setName and setAge.

Exercise:

Write an application that provides a list manager for a school class. The teacher is presented with a menu that invites him/her to choose to

(a) create the class list,

(b) add a name to the list,

(c) delete a name from the list,

(d) display the list on the screen and

(e) exit from the application.

Assume that the list is maintained in alphabetical order of students’ surnames and that all name strings

are in the form “SurnameForename”.

Exercise 2:

In this exercise you first design a Person class that allows Person objects to be created to keep track of people and their favourite colours (or indeed any relevant pieces of information about the people). The teaching material at this link:

should help you.

Then you design a linked list of class Person objects. The list starts off empty and can be added to as you accumulate friends and wish to keep a note of their favourite colours (or something more serious, and less childish). If you fall out with someone you can delete them from your list. If you acquire a new friend you can add them to the list at the correct alphabetical position. You can print out all the friends you have, alphabetically, together with their favourite colour. If you forget one of your friend’s favourite colour you interrogate the list.

In effect you’re creating a list manager.

Provide a menu so that the user can choose the options:

1. add,

2. delete,

3. search.

4. printout

5. exit

Before you tackle this exercise, have regard to the following notes:

Part 6: Using your own classes with Java’s collection classes

In the examples above, we’ve stuck to the pre-defined String type for the type of objects used in the List classes. However, as briefly mentioned already, objects of any class can be used inside these lists, including objects of your own classes. Care needs to be taken when using your own classes.

If you wish to use objects of your own class as objects in Java’s collection classes, and you wish to System.out.println an object of the List class, a meaningful toString method should be defined in your own class, i.e. the one for the sorts of objects the list contains. Thus if the list has Rectangles in it, there should be a toString method for Rectangles. We’ll see this later on. The toString method tells the objects how they should show themselves on the screen.

Consider the Rectangle class that you’ve already studied. For example, let’s suppose we had a list of Rectangle objects

List ourOblongs = new ArrayList();

I’ve chosen ourOblongs as the name of the list, given that oblong is another word for rectangle. As far as the computer is concerned I could have called the list something like banana or chewingGum, but from a human perspective, that probably wouldn’t make much sense, in this context.

If we issue the command

System.out.println(ourOblongs);

Then a meaningful toString method must be supplied for our Rectangle class so that System.out.println will know what to do

We could have:

public String toString()

{

return "{" + l + ", "+ b +"}";

}

where l and b are the two attributes that each Rectangle object has as its attributes.

Thus if we had the line

System.out.println(ourOblongs);

we might see something like:

[{3, 4}, {5, 9}, {2, 4}]

if it happened to be that these three rectangles were in the list. This is because each Rectangle knows to display itself with curly brackets surrounding its length and breadth, separated by commas. We could have chosen another way of our choice that Rectangle objects would use to display themselves.

Part 7: Defining an equals method

If we wish to send lists messages such as contains and remove, we’ll need each object in the list to have its own equals method. We already have an equals method for our Rectangle class; see the notes in Chapter 4 on the class home page.

Part 8: A complete set of software to illustrate the above discussion

/* a list of rectangles

Date: 6th March 2010

Ian Downey

*/

import java.util.*; // Java library for linked lists referenced here

class Rectangle

{

int l, b;

// method to respond to a message sent

// to a rectangle to set its length

public void setLength(int lengthValue)

{

l = lengthValue;

}

// method to respond to a message sent

// to a rectangle to set its breadth

public void setBreadth(int breadthValue)

{

b = breadthValue;

}

// method to allow a Rectangle to respond

// to a System.out.println

public String toString()

{

return("{" + l + "," + b + "}");

}

}

public class UseRectangle

{

public static void main(String [] args)

{

// ask for a LinkedList for storage of rectangles

// to be constructed

List oblong = new LinkedList();

// ask for three rectangles to be constructed

Rectangle r1 = new Rectangle();

Rectangle r2 = new Rectangle();

Rectangle r3 = new Rectangle();

// send messages to the rectangles to tell them

// what lengths and breadth to take

r1.setLength(4);

r1.setBreadth(5);

r2.setLength(6);

r2.setBreadth(7);

r3.setLength(8);

r3.setBreadth(9);

// add the rectangles to the list

oblong.add(r1);

oblong.add(r2);

oblong.add(r3);

// print out rectangle r1 (same idea for r1 and r2

System.out.println("Just one point:");

System.out.println(r1);

// blank line

System.out.println();

// print out the list of rectangles

System.out.println("A list of points:");

System.out.println(oblong);

// blank line

System.out.println();

// create a pointer to the list

ListIterator r = oblong.listIterator();

// we work our way through the list, using the pointer, to print it out

while(r.hasNext())

System.out.println(r.next());

}

}

Part 9: The software above repeated with the facility to search for a Rectangle of the user’s choice:

The software below is the same as that above, except that the list is made twice as long and there’s a section inviting the user to type in values for length and breadth of a rectangle and then a report will be given to the user as to whether or not a list of those dimensions is in the list.

/* a list of rectangles

Date: 3rd March 2010

Ian Downey

*/

import java.util.*; // Java library for linked lists referenced here

class Rectangle

{

int l, b;

// method to respond to a message sent

// to a rectangle to set its length

public void setLength(int lengthValue)

{

l = lengthValue;

}

// method to respond to a message sent

// to a rectangle to set its breadth

public void setBreadth(int breadthValue)

{

b = breadthValue;

}

// method to allow a Rectangle to respond

// to a System.out.println

public String toString()

{

return("{" + l + "," + b + "}");

}

// method to allow a Rectangle object to say whether it's equal to another rectangle or

// not. Note the use of the Boolean AND operator &&. See also Chapter 4: Rectangle class.

public boolean equals(Rectangle rIn)

{

return l == rIn.l && b == rIn.b;

}

}

public class UseRectangle

{

public static void main(String [] args)

{

// ask for a LinkedList for storage of rectangles

// to be constructed

List oblong = new LinkedList();

// ask for three rectangles to be constructed

Rectangle r1 = new Rectangle();

Rectangle r2 = new Rectangle();

Rectangle r3 = new Rectangle();

Rectangle r4 = new Rectangle();

Rectangle r5 = new Rectangle();

Rectangle r6 = new Rectangle();

// send messages to the rectangles to tell them

// what lengths and breadth to take

r1.setLength(4);

r1.setBreadth(5);

r2.setLength(7);

r2.setBreadth(6);

r3.setLength(7);

r3.setBreadth(9);

r4.setLength(2);

r4.setBreadth(9);

r5.setLength(1);

r5.setBreadth(8);

r6.setLength(9);

r6.setBreadth(2);

// add the rectangles to the list

oblong.add(r1);

oblong.add(r2);

oblong.add(r3);

oblong.add(r4);

oblong.add(r5);

oblong.add(r6);

// print out rectangle r1 (same idea for r1 and r2)

System.out.println("Just one rectangle:");

System.out.println(r1);

// blank line

System.out.println();

// print out the list of rectangles

System.out.println("A list of rectagles:");

System.out.println(oblong);

// blank line

System.out.println();

// navigate through the list and print it out

ListIterator rA = oblong.listIterator();

while(rA.hasNext())

System.out.println(rA.next());

// construct a new Rectangle object and we'll see if it's in the list

Rectangle r7 = new Rectangle();

int lengthIn, breadthIn;

// ask the user for the length and the breadth of the new Rectangle

System.out.println("\nPlease type in values for length and breadth and ");

System.out.println("we'll tell you if a rectangle of these dimensions ");

System.out.println("is in the list.\n");

System.out.println("Length.");

lengthIn = Keyboard.readInt();

System.out.println("Breadth.");

breadthIn = Keyboard.readInt();

// tell the new Rectangle to have the values the user typed in

r7.setLength(lengthIn);

r7.setBreadth(breadthIn);

// navigate through the list and seek for the user's chosen rectangle

ListIterator rB = oblong.listIterator();

// assume it won't be found; it is is, then found will be changed to true

boolean found = false;

while(rB.hasNext())

{

if(rB.next().equals(r7))

{

System.out.println("The rectangle you're looking for ");

System.out.println(" is in the list.");

found = true;

}

}

// report to the user if it isn't found

if(found == false)

System.out.println("Sorry; the rectangle you're looking for isn't in the list.");

System.out.println("\n\n\n");

}

}

Exercises:

1. The software above for the Rectangle class has setter methods for both length and breadth. Write getter methods for both length and breadth and add them to the existing software.

2. Invite the user to type in a length and report whether there is at least one Rectangle with that length.

Part 10: Menu-driven list processing software 1

Constructor:

The software below has an additional section of code in the Rectangle pattern, in blue, and software to use it in purple. This is to allow new Rectangle objects to be built from their components, i.e. a length and a breadth.

Menu:

In addition the software has a menu. The menu continually:

(a) presents the end-user with a menu of options,

(b) allows the user to choose an option from the list,

(c) processes the option chosen and

(d) presents the menu again.

…and so on round and round.

Run the software to see what I mean. You’ll see that one of the options presented each time is to quit, so the user is not trapped forever in the loop.

You’ll notice a do…while loop in the software. (The do is near the top of the program and the while is close to the end.). It’s this loop that provides the repetition involved in this program. Essentially what’s going on is:

do

{

present menu;

get user’s choice;

process user’s choice;

while(user hasn’t chosen to end);

The do while is like a while except that what’s inside the loop (between curly brackets) must be done at least once, whereas in a while there’s a possibility of never getting an opportunity to do what’s inside the loop, if the loop condition is false at the very start.

/* menu-driven rectangle accumulation and listing program

Date: 6th March 2010

Ian Downey

*/

import java.util.*; // Java library for linked lists referenced here

class Rectangle

{

int l, b;

// method to allow a new Rectangle to be made

public Rectangle(int lIn, int bIn)

{

l = lIn;

b = bIn;

}

// method to respond to a message sent

// to a rectangle to set its length

public void setLength(int lengthValue)

{

l = lengthValue;

}

// method to respond to a message sent

// to a rectangle to set its breadth

public void setBreadth(int breadthValue)

{

b = breadthValue;

}

// method to allow a Rectangle to respond

// to a System.out.println

public String toString()

{

return("{" + l + "," + b + "}");

}

// method to allow a Rectangle object to say

// whether it's equal to anothe rectangle or

// not

public boolean equals(Rectangle rIn)

{

return l == rIn.l && b == rIn.b;

}

}

public class UseRectanglem

{

public static void main(String [] args)

{

// ask for a LinkedList for storage of rectangles

// to be constructed

List oblong = new LinkedList();

int lengthIn, breadthIn;

int choice;

do

{

System.out.println("\nplease choose your menu choice\n");

System.out.println("add a rectangle \t 1");

System.out.println("list rectangles \t 2");

System.out.println("quit \t\t\t 0");

System.out.println("\n");

choice = Keyboard.readInt();

if(choice == 1)

{

// ask the user for the length and the breadth of the new Rectangle

System.out.println("\nPlease type in values for length and

breadth");

System.out.println("Length.");

lengthIn = Keyboard.readInt();

System.out.println("Breadth.");

breadthIn = Keyboard.readInt();

oblong.add(new Rectangle(lengthIn, breadthIn));

}

else if (choice == 2)

// code for printing out the list of rectangles

System.out.println(oblong);

}while(choice != 0);

System.out.println("\n\nthank you for using this program.\n\n");

}

}

Part 11: Menu-driven list processing software 2

The software below continues to have an additional section of code in the Rectangle pattern, in blue, and software to use it in purple. As explained before, this software, in blue, allows new Rectangle objects, in blue, to be made, in purple.

/* menu-driven rectangle accumulation, listing and deletion program

Date: 6th March 2010

Ian Downey

*/

import java.util.*; // Java library for linked lists referenced here

class Rectangle

{

int l, b;

// method to allow new Rectangles to be made

public Rectangle(int lIn, int bIn)

{

l = lIn;

b = bIn;

}

// method to respond to a message sent

// to a rectangle to set its length

public void setLength(int lengthValue)

{

l = lengthValue;

}

// method to respond to a message sent

// to a rectangle to set its breadth

public void setBreadth(int breadthValue)

{

b = breadthValue;

}

// method to allow a Rectangle to respond

// to a System.out.println

public String toString()

{

return("{" + l + "," + b + "}");

}

// method to allow a Rectangle object to say

// whether it's equal to another rectangle or

// not.

public boolean equals(Rectangle rIn)

{

return l == rIn.l && b == rIn.b;

}

}

public class UseRectanglem

{

public static void main(String [] args)

{

// ask for a LinkedList for storage of rectangles

// to be constructed

List oblong = new LinkedList();

ListIterator e;

int lengthIn, breadthIn, choice;

do

{

System.out.println("\nplease choose your menu choice\n");

System.out.println("add a rectangle \t 1");

System.out.println("list rectangles \t 2");

System.out.println("remove a rectangle \t 3");

System.out.println("quit \t\t\t 0");

System.out.println("\n");

choice = Keyboard.readInt();

if(choice == 1)

{

// ask the user for the length and the breadth of the new Rectangle

System.out.println("\nPlease type values for length & breadth");

System.out.println("of rectangle to be added.");

System.out.println("Length.");

lengthIn = Keyboard.readInt();

System.out.println("Breadth.");

breadthIn = Keyboard.readInt();

oblong.add(new Rectangle(lengthIn, breadthIn));

}

else if (choice == 2)

// code for printing out the list of rectangles

System.out.println(oblong);

else if (choice == 3)

{

// ask the user for the length and the breadth of the Rectangle

System.out.println("\nPlease type in values for length and

breadth");

System.out.println("of rectangle to be removed.");

System.out.println("Length.");

lengthIn = Keyboard.readInt();

System.out.println("Breadth.");

breadthIn = Keyboard.readInt();

e = oblong.listIterator();

while(e.hasNext())

{

if(e.next().equals(new Rectangle(lengthIn, breadthIn)))

{

e.previous(); // go back to reverve effects of

//next()

e.remove(); // now remove the appropriate one

}

}

}

}while(choice != 0);

System.out.println("\n\nthank you for using this program.\n\n");

}

}

The line

if(e.next().equals(new Rectangle(lengthIn, breadthIn)))

in the code above is based on the fact that e.next() is the next Rectangle pointed to in the list and we ask it whether or not it’s equal to the Rectangle newly constructed out of raw materials (see purple writing). If it is, true is sent back; if it isn’t false is sent back. The if then goes ahead on the basis of the true or the false that it sees in its set of round brackets.

Part 12: Menu-driven list processing software 3

/* menu-driven rectangle listing program with checking against adding multiple entries and attempting to delete a Rectangle that isn’t there. (see purple text below)

Date: 6th March 2010

Ian Downey

*/

import java.util.*; // Java library for linked lists referenced here

class Rectangle

{

int l, b;

// method to allow new Rectangles to be made

public Rectangle(int lIn, int bIn)

{

l = lIn;

b = bIn;

}

// method to respond to a message sent

// to a rectangle to set its length

public void setLength(int lengthValue)

{

l = lengthValue;

}

// method to respond to a message sent

// to a rectangle to set its breadth

public void setBreadth(int breadthValue)

{

b = breadthValue;

}

// method to allow a Rectangle to respond

// to a System.out.println

public String toString()

{

return("{" + l + "," + b + "}");

}

// method to allow a Rectangle object to say

// whether it's equal to anothe rectangle or

// not

public boolean equals(Rectangle rIn)

{

return l == rIn.l && b == rIn.b;

}

}

public class UseRectanglemn

{

public static void main(String [] args)

{

// ask for a LinkedList for storage of rectangles

// to be constructed

List oblong = new LinkedList();

ListIterator e;

Rectangle r; // will be a newly constructed rectangle object

int lengthIn, breadthIn; // will hold the l and b of a new rectangle

int choice; // menu choice

boolean there; // whether something to be inserted is already there

// menu provided:

// 1. add a rectangle to the list, if it isn’t already there

// 2. list rectangles

// 3. remove a rectangle from the list if it’s there

// 0. quit the program

do

{

System.out.println("\nplease choose your menu choice\n");

System.out.println("add a rectangle \t 1");

System.out.println("list rectangles \t 2");

System.out.println("remove a rectangle \t 3");

System.out.println("quit \t\t\t 0");

System.out.println("\n");

choice = Keyboard.readInt();

if(choice == 1) // 1. add a rectangle to the list

{

// ask the user for the length and the breadth of the new Rectangle

System.out.println("\nPlease type in values for length and ");

System.out.println("breadth of rectangle to be added.");

System.out.println("Length.");

lengthIn = Keyboard.readInt();

System.out.println("Breadth.");

breadthIn = Keyboard.readInt();

r = new Rectangle(lengthIn, breadthIn); // make the new rectangle

// check to see if the new rectangle is already there

there = false; // assume at first that it won’t be

e = oblong.listIterator();

while(e.hasNext())

{

// ask the next rectangle in the list if it’s equal

// to the one we plan to add:

if(e.next().equals(r))

there = true; // ah! it’s there already.

}

// add it if it's not there already

if(there == false)

oblong.add(r);

}

else if (choice == 2) // 2. print out the list

// code for printing out the list of rectangles

System.out.println(oblong);

else if (choice == 3) // 3. remove a rectangle

{

// ask the user for the length and the breadth of the Rectangle

System.out.println("\nPlease type in values for length and ");

System.out.println("breadth of rectangle to be removed.");

System.out.println("Length.");

lengthIn = Keyboard.readInt();

System.out.println("Breadth.");

breadthIn = Keyboard.readInt();

e = oblong.listIterator();

there = false; // assume at first it won’t be there.

while(e.hasNext())

{

if(e.next().equals(new Rectangle(lengthIn, breadthIn)))

{

there = true; // Ah, it is there! So let’s remove it:

e.previous(); // oops! gone too far; go back one

e.remove(); // now remove the appropriate one

// the job’s been done! Cool!

}

}

if(there == false)

{

System.out.println("\nThe rectangle you want ");

System.out.println("removed isn’t in the list! \n");

}

}

}while(choice != 0); // while user hasn’t yet chosen to quit.

System.out.println("\n\nthank you for using this program.\n\n");

}

}

Remember that the object e (my name; I could have called it anything I like) in the above code is a cursor to the list, allowing us to navigate through the list. When we send a next() message to e, we make it move along the list to which it’s pointing one step to the right. When we send a previous() message to e we make it move along the list to which it’s pointing one step to the left.

The line

if(e.next().equals(r))

in the code above is based on the fact that e.next() is the next Rectangle pointed to in the list and we ask it whether or not it’s equal to the Rectangle called r. If it is, true is sent back; if it isn’t false is sent back. The if then goes ahead on the basis of the true or the false that it sees in its set of round brackets.

Check list of things you need to know from this entire document:

toString methods

equals method

designing menus

The message that can be sent to strings

The messages that can be sent to iterators

The messages that you decide can be sent to objects of your own home-made classes

etc

Appendix:

In the above notes we’ve looked at some of the messages that can be sent to (a) lists (b) iterators and (c) Strings. Here these messages are listed:

(a) Messages that can be sent to lists:

add, add, set, get, indexOf, remove, remove, contains, isEmpty, size, listIterator

(b) Messages that can be sent to iterators:

next, previous, hasNext, add, remove

(c) Messages that can be sent to Strings:

equals, compareTo

(Search through the notes in this entire document to see if there are any messages that I’ve omitted.)

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download