Documente Academic
Documente Profesional
Documente Cultură
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
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>();
type String:
primitive type.
myList.add("Eric");
myList.add("Bob");
myList.add("Steve");
This will make "Eric" the first element, "Bob" the second
myList.remove(1);
Note: This will remove the second element and all elements behind that
To insert an element into a specific index you use the add method
myList.add(3, "Chris");
This will add "Chris" to the list at index 3 and all elements with indices
myList.set(2, "Joe");
This will replace the value of the element at index 2 with the value
"Joe".
Example: ArrayListInsertRemoveReplace.java
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
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.
stream)
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;
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!
myFile.txt:
Writing to a File
Important Note: Creating a PrintWriter object throws
methods header:
Import java.io.FileNotFoundException
import java.io.FileNotFoundException;
line character.
print prints its argument to the file
When you are finished writing to the file, you must close it
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.
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:
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