0% found this document useful (0 votes)
9 views

Lecture4

This lecture covers the concept of lists in programming, specifically focusing on LinkedLists, their structure, manipulation methods, and the use of iterators. It also introduces enhanced for loops and enums, explaining how to declare and utilize them in Java. Key features include adding, removing elements, type casting, and iterating through collections effectively.

Uploaded by

koximi1998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lecture4

This lecture covers the concept of lists in programming, specifically focusing on LinkedLists, their structure, manipulation methods, and the use of iterators. It also introduces enhanced for loops and enums, explaining how to declare and utilize them in Java. Key features include adding, removing elements, type casting, and iterating through collections effectively.

Uploaded by

koximi1998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Information Technology

Applications Programming

LECTURE 4
Lists

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Lists
Learning Objectives
At the end of the lecture, you should be able to:

 Describe a list, its structure and features


 Describe and use type casting
 Understand how a LinkedList is used including commonly used
methods
 Understand what an iterator does
 Use enhanced for loops
 Describe and use an enum

WU Chapters 16.1-16.4 & 5.7

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

What is a List ?

A list is an ordered collection of elements (objects)

 It has a collection of cells, each with a


pointer to the element and a pointer to
the next cell
 A user can access elements in the list by
their index (position) and search the list
for a specific element
 Identical elements can be used in a list
(unlike arrays)

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

1
List Structure
A List can be:
• one way – last cell has a null pointer

• or two way – has both next and last pointer

 Diagrams Courtesy of Dr. Robert Rist, UTS

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

List Manipulation
Elements can be added and deleted
 Add

 Delete

 Diagrams Courtesy of Dr. Robert Rist, UTS


INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

List Features

Class LinkedList implements a two way list

add(Object o) appends objects to the end of the list

remove(Object o) removes the first instance of an element from the list –


there can be more than one object matching “o”

clear() removes all objects from the list

size() returns the number of elements in the list

get(int index) returns the object at the given index

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

2
A Simple List

We can create a LinkedList and add some objects

LinkedList rectangles = new LinkedList();


rectangles.add(new Rectangle(2.0, 3.0);
rectangles.add(new Rectangle(3.0, 4.0);
rectangles.add(new Rectangle(4.0, 5.0);

 The list has 3 objects, so rectangles.size() will return 3

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Retrieving Objects from a List

rectangles.get(2); will retrieve the 3rd element in the list

 We have not declared the type of objects in our list, so we


must cast the retrieved object to a Rectangle if we want to
access the Rectangle methods.

Rectangle rectangle = (Rectangle) rectangles.get(2);


rectangle.area();

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Review of Casting
In IPRG001, you used casting on primitive data types

• int result = (int)(height*length);


• This uses height (as a double)
Simple Cast then casts the multiplication
result to an int

• int result = ((int)height)*length


Immediate • This casts height to an int before
it is used in multiplication
Cast
INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

3
Casting Object references

We can cast to

Rectangle rectangle = (Rectangle) rectangles.get(2);

 An object can be cast to any other class in its hierarchy tree


(that is, subclass or superclass)

 Remember: All classes inherit from Object unless a parent


class is specified (using implementation inheritance)

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

A LinkedList with Declared Type

Since the rectangles list only contains Rectangle objects, we can


declare the type of objects held by the list

LinkedList<Rectangle> rectangles = new LinkedList<Rectangle>();


rectangles.add(new Rectangle(2.0, 3.0);
rectangles.add(new Rectangle(3.0, 4.0);
rectangles.add(new Rectangle(4.0, 5.0);

 Now we can retrieve the objects as Rectangle objects


without casting
Rectangle rectangle = rectangles.get(2);
rectangle.area();

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

List Iterator
A list iterator (itr or litr) retrieves an element from the list

• hasNext() – boolean – returns


true if another element exists
Iterator in the list (in a forward
direction)

methods • next() – returns current


element and moves to the next
element in the list

A basic iterator returns an object as type Object – so the


returned object must be cast
Or the elements in the ListIterator must have a type
declared ie ListIterator <Rectangle>
INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

4
LinkedList Iterator Methods
add(Object O) inserts element into the list

hasNext() checks if the next element exists

hasPrevious() checks if the previous element exists

next() returns the next element in the list

previous() returns the previous element in the list

remove() removes the last element returned using next() or previous()

set(Object o) replaces the last element returned with the specified element

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Quick Quiz
With a partner, discuss and answer these questions:

 What method would you use to delete all elements in a


LinkedList ?
 What does a list iterator do ?
 What method would you use to remove the current element
from a LinkedList, using the LinkedList Iterator?

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Retrieving Elements Using an Iterator

ListIterator<Rectangle> li = rectangles.listIterator();
Rectangle rectangle1 = li.next(); //1st element in list
Rectangle rectangle2 = li.next(); //2nd element in list
Rectangle rectangle3 = li.next(); //3rd element in list

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

5
Iterating through a List
We can use a while loop to iterate through elements in the list
ListIterator<Rectangle> li = rectangles.listIterator();
while (li.hasNext())
{
Rectangle current = li.next();
System.out.println("Area is:" + current.area());
System.out.println("Perimeter is:" + current.perimeter());
}

Results:
Area is:6.0 – this is the first object
Perimeter is:10.0
Area is:12.0 – this is the second object
Perimeter is:14.0
Area is:20.0 – this is the third object
Perimeter is:18.0

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Enhanced for loop


 In IPRG001, you used for loops like this

for(initialisation;exit condition;increment)

• Semi colon separation


 Java also allows for-each loops like this

for (element:collection)

• Colon separation

 For-each loops should be used where possible

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

For-each Loop Example

You can also use a for-each loop for an array

int[] numbers = {1,2,3,4,5,6,7,8,9,10};


for (int item : numbers)
{
System.out.println("Count is: " + item);
}

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

6
For-each Object Array Example

Customer[] customers = {new Customer(”Peter”),


new Customer(“Bill”) };
for (Customer customer : customers)
{
System.out.println("Customer is: " + customer.getName());
}

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

For-each LinkedList Example

LinkedList<Customer> customers =
new LinkedList<Customer>();
customers.add(new Customer(" Peter "));
customers.add(new Customer(" Bill "));

for (Customer customer : customers)


{
System.out.println("Customer is: " + customer.getName());
}

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Loop Exits

• continue – jump to
Loop the end of the loop
• break – exit the loop
Exits • return – exit the loop
and the method

 In most cases, it is better to have a loop end naturally using the


condition. It is more readable. Sometimes we will use a return, if
we find what we want and don’t need to keep iterating.

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

7
Enum
Is an enumerated data type, that is, you can declare a list of
constants that the runtime will treat as numbers.

 Example:

public enum Direction { NORTH, SOUTH, EAST, WEST }

 enum inherits from the Enum class in the API, so you


cannot inherit from any other class.
 An enum class has a private constructor, that cannot be
invoked, the runtime uses it to create the constants.
 enum is a type of singleton (only allows 1 instance at any
time)
INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Simple Enum Example

 Declare a private datatype

private enum Days { SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};

 Declare an attribute to hold the value


private Days today;
 Set the value of the attribute
today = Days.SUNDAY;
 Test the value
if (today == Days.SUNDAY)
 Iterate through each enum value
for (Days day : Days.values())

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Complex Enum

An enum is a class, so you can add methods and attributes to it.


Each field can have values for each attribute.

public enum Suit


{
DIAMONDS("Diamond"),
CLUBS("Club"),
HEARTS("Heart"),
SPADES("Spade"); //notice the semicolon here

private final String name;


private Suit(String name) { this.name = name; }
public String getName() { return name; }
}

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

8
Complex Enum
 Here we have an attribute called name, each field in the enum
has a value for name that is set when the constructor is called
by the runtime.
– ie HEARTS:name has a value of “Hearts”.
 The public method getName() can be called to retrieve the
attribute value for each field.

for (Suit suit : Suit.values())


{
System.out.println(suit.getName());
}

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Collections

A collection is an object that groups multiple elements


together.

 A collection is used to store, retrieve and manipulate data


elements of the group.
 A LinkedList holds a collection of objects

LinkedList<Rectangle> rectangles = new LinkedList<Rectangle>();

 When we declare <Rectangle>, we are declaring the type of


collection the LinkedList will hold.

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

Key Concepts
Summary
 A list can be one way or two
way
 LinkedList implements a two
way list
 A ListIterator retrieves an
object from a list
 Enhanced for loop
for(element : collection)
 An enum can be simple or
complex

INSEARCH CRICOS provider code: 00859D I UTS CRICOS provider code: 00099F

You might also like