- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 2323字
- 2021-06-11 13:05:24
Lists
Lists are ordered collections of data. Unlike sets, lists can have repeated data. Having data contained within lists allows you to perform searches that will give the locations of certain objects within a given list. Given a position, it is possible to directly access an item in a list, add new items, remove items, and even add full lists. Lists are sequential, which makes them easy to navigate using iterators, a feature that will be explored in full in a later section in the chapter. There are also some methods for performing range-based operations on sublists.
There are two different list implementations: ArrayList and LinkedList. Each of them is ideal depending on the circumstances. Here, we will work with ArrayList mainly. Let's start by creating and populating an instance, then search for a certain value, and given its location within the list, we'll print out the value.
import java.util.*;
public class Example12 {
public static void main(String[] args) {
List list = new ArrayList();
list.add(35);
list.add(19);
list.add(11);
list.add(83);
list.add(7);
System.out.println(list);
int index = list.indexOf(19);
System.out.println("Find 19 at: " + index);
System.out.println("Component: " + list.get(index));
}
}
The output of this example is:
[35, 19, 11, 83, 7]
Find 19 at: 1
Component: 19
Process finished with exit code 0
The indexOf method informs you about the location of an object passed to the method as a parameter. It's sibling method, lastIndexOf, reports the location of the last occurrence of an object in the list.
You should look at a list as a series of nodes connected by links. If one of the nodes is eliminated, the link that used to point to it will be redirected to the following item in the list. When adding nodes, they will be attached by default at the end of the list (if they are not duplicated). As all the nodes in the collection are of the same type, it should be possible to exchange the locations of two nodes in a list.
Let's experiment with removing an item from a list and ascertaining the locations for objects located immediately before and after the removed item:
import java.util.*;
public class Example13 {
public static void main(String[] args) {
List list = new ArrayList();
list.add(35);
list.add(19);
list.add(11);
list.add(83);
list.add(7);
System.out.println(list);
int index = list.lastIndexOf(83);
System.out.println("Before: find 83 at: " + index);
list.remove(index - 1);
System.out.println(list);
index = list.lastIndexOf(83);
System.out.println("After: find 83 at: " + index);
}
}
This program creates a list, prints it out, looks for a node in the list, and prints its location. Then, it removes an item in the list and repeats the previous process to show that the node has been removed from the list. This is a clear difference from the case with arrays, where it is not possible to remove items from them, and thus it is not possible to change their size. Observe the output of the previous example:
[35, 19, 11, 83, 7]
Before: find 83 at: 3
[35, 19, 83, 7]
After: find 83 at: 2
Process finished with exit code 0
It is also possible to change the content of a node. In the previous example, instead of removing a node, change list.remove(index-1); to the following and check the outcome:
list.set(index - 1, 99);
The final array will have substituted 11 for 99.
If instead of deleting one node, you wanted to empty the whole list, the command to the issue would be:
list.clear();
Using subList(), an operator that generates lists from lists, it is possible to, for example, delete a range of cells within a list. See the following example, which deletes part of a string array, changing its meaning when printing it:
import java.util.*;
public class Example14 {
public static void main(String[] args) {
List list = new ArrayList();
list.add("No");
list.add("matter");
list.add("what");
list.add("you");
list.add("do");
System.out.println(list);
list.subList(2,4).clear();
System.out.println(list);
}
}
Look at the following result:
[No, matter, what, you, do]
[No, matter, do]
Process finished with exit code 0
The list object has been modified by running the example code so that it becomes shorter. The two index numbers used in the subList() method is the places in the list where the method starts and stops. The result of subList() can also be assigned to a different variable of the same List type, resulting in a reduced copy of the list in the code, after performing the subList() operation.
Look at the following modification in the latest code listing:
List list1 = list.subList(2,4);
System.out.println(list1);
This will print out the list that was made of the nodes that were deleted in the previous example.
There are a lot of interesting algorithms within the collections framework that offers relevant functionality for operating with lists:
- sort: Put the elements of a list in a certain order.
- shuffle: Randomize the locations of all objects in a list.
- reverse: Invert the order of a list.
- rotate: Move objects to the end of a list, and when they reach the end, have them show up at the other end.
- swap: Swap two elements with one another.
- replaceAll: Replace all occurrences of an element in a list using a parameter.
- fill: Fill the content of a list with one value.
- copy: Make more instances of a list.
- binarySearch: Perform optimized searches within a list.
- indexOfSubList: Search for the occurrence of a piece (a set of consecutive nodes) of a list.
- lastIndexOfSubList: Search for the last occurrence of a piece of a list.
Note
Lists generated from arrays using Arrays.asList() do not behave in the same way as the objects of the List class described in this section. The lists coming from arrays have a fixed length, which means that elements cannot be removed from the array. The reason for this is that java.util.Arrays implement its own ArrayList class inside the package, one that is different from the one in the collections framework. Confusing, isn't it?
Exercise 1: Creating the AnalyzeInput Application
In this exercise, we will create a new application that will respond to the CLI by storing whatever strings are provided to it, then run some statistical operations on the data, such as word counting (determining the most frequent word or the most frequent letter, and so on). The intent is to give you an idea of how to use the collections framework instead of other tools to do such operations. This time, we will do something special; instead of getting the data from the CLI as arguments to the script, we will use the java.io.Console API, which allows the reading of different types of strings from the terminal, such as usernames (plain strings) and passwords. The goal of this application is to read the input until a line with only the "*" symbol (asterisk) is captured. Once the termination symbol is entered, the text will be processed, and the statistics will be delivered to the terminal:
- Open IntelliJ and create a new Java program using the CLI template. Name the project AnalyzeInput.
- Start by creating a simple program that can read a line from the terminal and printing it out:
import java.io.Console;
public class AnalyzeInput {
public static void main(String[] args) {
Console cons;
String line = "";
if ((cons = System.console()) != null && (line = cons.readLine()) != null) {
System.out.println("You typed: " + line);
}
}
}
- Execute the program from the CLI by calling java AnalyzeInput from the right folder and interact with it:
usr@localhost:~/IdeaProjects/ch04/out/production/ch04$ java AnalyzeInput
hej this is an example
You typed: hej this is an example
- You must import java.io.Console, which allows you to instantiate objects of the Console class. You can also see the call to cons = System.console(), which will make sure that the terminal is ready for you to read the data, and line = cons.readLine(), which will ensure that when hitting the Enter key on the keyboard, the resulting data is not empty.
- The next step is storing the data we are capturing in a collection. Since we don't know the size this could be, we should be using ArrayList <String> to store the data. Also, to store data for as long as we want, we can modify the if statement and make it into a while loop. Finally, use the add method to add the lines into a list (note that the following code listing will never exit, so bear with us and do not execute it yet):
import java.util.*;
import java.io.Console;
public class Exercise01 {
public static void main(String[] args) {
ArrayList <String> text = new ArrayList<String>();
Console cons;
String line = "";
while ((cons = System.console()) != null && (line = cons.readLine()) != null) {
text.add(line);
}
System.out.println("You typed: " + text);
}
}
- Modify the while loop to include the condition we established for finishing the data capture process – the arrival of a line with only an asterisk symbol:
while (!line.equals("*")
&& (cons = System.console()) != null
&& (line = cons.readLine()) != null) {
- The outcome will happen only when you type the asterisk symbol alone in a line, as seen in this log while interacting with the program:
usr@localhost:~/IdeaProjects/ch04/out/production/ch04$ java AnalyzeInput
this is the array example
until you type *
alone in a line
*
You typed: [this is the array example, until you type *, alone in a line, *]
- Since we used ArrayList to store the different strings, you could be typing until you exhaust the computer's memory. Now it is possible to execute some commands to work with the strings. The first step will be turning the whole of the text into a list. This will require going through the different strings and splitting them into parts that will be added to a larger list. The easiest trick is to use the split() method using a whitespace character as a separator. Modify the main method to look like the following, and you will see that the result is now a list with all the words separated as single nodes in the list:
public static void main(String[] args) {
ArrayList <String> text = new ArrayList<String>();
Console cons;
String line = "";
while (!line.equals("*")
&& (cons = System.console()) != null
&& (line = cons.readLine()) != null) {
List<String> lineList = new ArrayList<String>(Arrays.asList(line.split(" ")));
text.addAll(lineList);
}
System.out.println("You typed: " + text);
}
- Having all the data stored in this way allows for the use of a lot of the methods available in the collections framework that will let you do operations with data. Let's start by counting all the words in the text (including the closing symbol, "*"). Just add the following at the end of the main method:
System.out.println("Word count: " + text.size());
The result of this exercise is a program that is ready to be used for further analysis of the data. But in order to continue doing so, we need to make use of a tool that has not yet been introduced—the iterator. We will come back to this example later in the chapter and finish off the application by adding some extra functionality to it.
- Mastering Visual Studio 2017
- Visual C++程序設(shè)計(jì)教程
- 案例式C語(yǔ)言程序設(shè)計(jì)
- Oracle從新手到高手
- C++面向?qū)ο蟪绦蛟O(shè)計(jì)(微課版)
- 深入淺出Prometheus:原理、應(yīng)用、源碼與拓展詳解
- Mastering Articulate Storyline
- 3D少兒游戲編程(原書(shū)第2版)
- C程序設(shè)計(jì)案例教程
- 基于Swift語(yǔ)言的iOS App 商業(yè)實(shí)戰(zhàn)教程
- Python機(jī)器學(xué)習(xí)經(jīng)典實(shí)例
- Drupal 8 Module Development
- 零基礎(chǔ)學(xué)Python網(wǎng)絡(luò)爬蟲(chóng)案例實(shí)戰(zhàn)全流程詳解(入門(mén)與提高篇)
- Python Data Analysis Cookbook
- 區(qū)塊鏈技術(shù)與應(yīng)用