Sei sulla pagina 1di 12

The ArrayList Class and File IO

CS0007: Introduction to Computer


Programming

The ArrayList Class


Array data structure:
Pro: Can access any element with its index
Con: Cannot add or remove elements (statically sized)

Linked list data structure


A linked list is a data structure in which an element of the list is

a node that references the next element in the list.


A node in a linked list is made up of some data and a reference to

another node.
Pro: Can add and remove elements (dynamically sized)
Con: Have to traverse list from beginning to find an element

Arrays are weak where linked lists are strong, and vice

versa. Is there any data structure to take advantage of


this.
Answer: Yes

The Java API provides a class called ArrayList.


An ArrayList is a data structure that is a combination of an

array and a linked list.

The ArrayList Class


ArrayLists contain elements that can be accessed by

their index, but also have advantages over arrays:


An ArrayList automatically expands as items are added to

it.
An ArrayList automatically shrinks as items are removed
from it.
To use an ArrayList, you must import it from the

java.util package:

import java.util.ArrayList;
The declaration and creation of an ArrayList follows this

form:
ArrayList<dataType> identifier = new ArrayList<dataType>();

So If I wanted to create an array list whose elements are of

type String:

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

Important Note: An ArrayList can only hold elements

that are objects.


That means an ArrayList cannot hold elements of a

primitive type.

The ArrayList Class


You can add items to the end of an ArrayList by using

the add method

myList.add("Eric");
myList.add("Bob");
myList.add("Steve");
This will make "Eric" the first element, "Bob" the second

element, and "Steve" the third element.


Like in an array, these elements have indices starting at 0.

To get the number of items stored in the ArrayList, use

the size method.


myList.size();
To get an element by its index, use the get method
myList.get(1);
Example: ArrayListExample.java

Enhanced for Loop and


ArrayLists
As stated previously, the enhanced for loop

iterates through the elements of any collection.


Weve seen this with arrays before:
String[] names = {"Eric", "Thomas", "Steve"};

for(String name : names) {


System.out.println(name);
}

We can also do this with ArrayLists.


Example: EnhancedForArrayList.java

The toString Method and


ArrayLists
Every class in Java inherits methods from a base

class called Object.

If you were to create a class, it would automatically

inherit these methods.


These methods are placeholders and do nothing meaningful

when you inherit them.


The point of these methods is to override them.
When you override an inherited method, you replace a
previous implementation of that method with another.
One of these methods is called toString.
toString is a method whose purpose is to return a String
representation of an object.
ArrayList has its own implementation of this.
Example: ArrayListToString.java

Inserting, Removing and Replacing


Elements
To remove an element from a list you use the remove method with the

index of the element you want to remove:

myList.remove(1);
Note: This will remove the second element and all elements behind that

element will move up in the list.


For example: If an element has index 5 before we remove the element at index 1,

after the removal, it will have index 4.

To insert an element into a specific index you use the add method

(similar to adding an element to the end of the list):

myList.add(3, "Chris");
This will add "Chris" to the list at index 3 and all elements with indices

greater than 2 will move back one.


For example: If an element has index 5 before we add the element at index 3, after

the addition, it will have index 6.

Finally, you can replace an element by using the set method:

myList.set(2, "Joe");
This will replace the value of the element at index 2 with the value

"Joe".

Example: ArrayListInsertRemoveReplace.java

Java File Input and Output


So far we have written programs, data could not be saved in

between runs of the program.


This is because the data weve used in our programs have been

stored in RAM.
Once our program is done running the data stored in RAM disappears.

In order for us to save data for use outside our programs or for

different runs of our programs, we must save our data outside of


RAM.
The most simple way of doing this is writing to a text file on the computers

hard drive.
In a text file all data is encoded as text, such as Unicode.
That way, when our program is finished executing, we will still have a
file with our data.

The steps taken when reading or writing to a file:


Open the file.
This opens a connection between the file and a program (often called a

stream)

Data is written or read from a file.


When the program is finished with the file, the file must be closed.

Two kinds of files in input and output:


Input File File in which data is read from.

Writing to a File
The Java API provides a class for writing to a file called

PrintWriter.
You must import the PrintWriter class.
import java.io.PrintWriter;

The general form to create a PrintWriter object:


PrintWriter identifier = new PrintWriter(fileName);

What is fileName?
It is the file you want to write to.
Text files typically have a .txt suffix
The file will be created in the directory in which the program was
compiled
o Note: This may be different places depending on the IDE you
use.
If the file already exists, it will be erased and overwritten!

So to create a FileWriter object that opens a file called

myFile.txt:

PrintWriter outputFile = new PrintWriter("myFile.txt");

Writing to a File
Important Note: Creating a PrintWriter object throws

an exception that must be handled.


We will not discuss exception handling in this course at length,

so just perform the following steps to allow your program to


compile:
Add the words throws FileNotFoundException to the end of the main

methods header:

public static void main(String[] args) throws FileNotFoundException

Import java.io.FileNotFoundException

import java.io.FileNotFoundException;

There are two methods that can be used to write to a file:


println prints its argument to the file and ends with a new

line character.
print prints its argument to the file
When you are finished writing to the file, you must close it

using the close method of the PrintWriter object.


Example: FileOutput.java

Reading from a File

To read from a file we need to use both the Scanner class and another class in
the Java API called File.
The File class is Javas way of representing a file in code.

For this we need to import both Scanner and File classes:


import java.io.File;
import java.util.Scanner;

Also we have to perform the steps to handle the FileNotFound exception, like
when we wrote to a file.
Next, we need to create both a File and Scanner objects:

File theFile = new File("myFile.txt");


Scanner inputFile = new Scanner(theFile);
This creates a File object that is associated with the file myFile.txt.
For now make sure this file is in the same directory that you compile your program from.
Again, this could be different depending on which IDE you use.
If the file does not exist, it will cause an error!

To read a single line from a file we can use the nextLine method on the
Scanner object.
Finally, to close the file we use the close method on the Scanner object.
Example: FileInput.java

Detecting the End of a File


It is often the case we want to read all of the

contents of the file, or simply keep reading from


the file until the end.
There is a method in the Scanner class that

detects if there is anything left to read in a file called


hasNext.
hasNext returns true if there is more to read in a file, or

false if there is not.


So this can be used in a loop to read all of the lines in a
file
o Example: HasNext.java

Potrebbero piacerti anche