官术网_书友最值得收藏!

Arrays

Arrays are part of the collections framework. There are some static methods that can be used to manipulate arrays. The operations you can perform are creating, sorting, searching, comparing, streaming, and transforming arrays. You were introduced to arrays in Chapter 2, Learning the Basics, where you saw how they can be used to store data of the same type. The declaration of an array is quite straightforward. Let's see what an array of strings would look like:

String[] text = new String[] { "spam", "more", "buy" };

Running operations on an array is as easy as calling some of the methods contained in the java.util.Arrays package. For example, sorting the previous array would require calling the following:

java.util.Arrays.sort( text );

The methods dedicated to handling arrays include one method that could be used to print out full arrays as if they were strings. This can be very handy when debugging a program:

System.out.println( java.util.Arrays.toString( text ) );

This will print the arrays and display each element separated by commas and within square brackets, []. If you executed the previous command after sorting the declared array of strings, the outcome would be:

[buy, more, spam]

As you can see, the array has been sorted in ascending alphabetical order. There is a difference between that way of printing out an array and using a for loop to iterate throughout an array:

for (int i = 0; i < text.length; i++)

    System.out.print(text[i] + " ");

This would give the following as the result:

buy more spam

If you want to write your code in a slightly cleaner way, you could import the whole java.util.Arrays API at the beginning of your program, which would allow you to call the methods by omitting the java.util part of the command. See the following example highlighting this technique:

import java.util.Arrays;

public class Example01 {

    public static void main(String[] args) {

        String[] text = new String[] { "spam", "more", "buy" };

        Arrays.sort(text);

        System.out.println(Arrays.toString(text));

        for (int i = 0; i < text.length; i++)

            System.out.print(text[i] + " ");

    }

}

The outcome will be:

[buy, more, spam]

buy more spam

Process finished with exit code 0

If you were to make a new array that you wanted to be filled up with the same data for all cells, there is the possibility of calling the java.util.Arrays.fill() method, as shown here:

int[] numbers = new int[5];

Arrays.fill(numbers, 0);

Such a command would create an array filled with zeros:

[0, 0, 0, 0, 0]

Creating arrays with prefilled data can also be done with a copy of a preexisting array. It is possible to create an array by copying part of one array, or by instantiating a larger one where the old one would just be part of it. Both methods are shown in the following example, which you can test in your editor:

import java.util.Arrays;

public class Example02 {

    public static void main(String[] args) {

        int[] numbers = new int[5];

        Arrays.fill(numbers, 1);

        System.out.println(Arrays.toString(numbers));

        int [] shortNumbers = Arrays.copyOfRange(numbers, 0, 2);

        System.out.println(Arrays.toString(shortNumbers));

        int [] longNumbers = Arrays.copyOf(numbers, 10);

        System.out.println(Arrays.toString(longNumbers));

    }

}

This example will print the numbers, shortNumbers (which is shorter), and longNumbers (which is longer) arrays. The newly added positions in the array will be filled with zeros. If it was an array of strings, they would be filled up with null. The outcome of this example is:

[1, 1, 1, 1, 1]

[1, 1]

[1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

Process finished with exit code 0

You can compare arrays by calling the java.utils.Arrays.equals() or java.util.Arrays.deepEquals() methods. The difference between them is that the latter can look through nested arrays. A simple comparison example of the former method in use follows:

import java.util.Arrays;

public class Example03 {

    public static void main(String[] args) {

        int[] numbers1 = new int[3];

        Arrays.fill(numbers1, 1);

        int[] numbers2 = {0, 0, 0};

        boolean comparison = Arrays.equals(numbers1, numbers2);

        System.out.println(comparison);

        int[] numbers3 = {1, 1, 1};

        comparison = Arrays.equals(numbers1, numbers3);

        System.out.println(comparison);

        int[] numbers4 = {1, 1};

        comparison = Arrays.equals(numbers1, numbers4);

        System.out.println(comparison);

    }

}

In this example, we create four arrays: numbers1, numbers2, numbers3, and numbers4. Only two of them are the same, containing three instances of 1. In the example, you can see how the last three arrays are compared to the first one. You can also see how the last array differs not in content, but in size. The outcome of this code is:

false

true

false

Process finished with exit code 0

Note

Since this chapter is not looking into such a complex data structure as nested arrays, we will not show an example of java.util.Arrays.deepEquals(). If you're interested, you should consider checking the Java reference at https://packt.live/2MuRrNa.

Searching within arrays is done through different algorithms behind the scenes. It is obviously a lot faster to perform searches on sorted arrays than on unsorted ones. The method to be invoked to run such a search on a sorted array is Arrays.binarySearch(). As it has many possible parameter combinations, it is recommended to visit the official documentation for the method. The following example illustrates how it works:

import java.util.Arrays;

public class Example04 {

    public static void main(String[] args) {

        String[] text = {"love","is", "in", "the", "air"};

        int search = Arrays.binarySearch(text, "is");

        System.out.println(search);

    }

}

This code is going to search for the word the inside the array text. The result is:

-4

Process finished with exit code 0

This is wrong! binarySearch is an optimized search algorithm within the collections framework, but it is not optimal when used with unsorted arrays. This means that binarySearch is mainly very useful for determining whether an object can be found within an array (by sorting it first). At the same time, we will need a different algorithm when we must search through unsorted arrays and when there are multiple occurrences of a value.

Try the following modification of the previous example:

String[] text = {"love","is", "in", "the", "air"};

Arrays.sort(text);

int search = Arrays.binarySearch(text, "is");

System.out.println(search);

The outcome, since the array is sorted, will be:

2

Process finished with exit code 0

It is only a coincidence in this case that "is" happens to be in the same place in the unsorted and the sorted versions of the array. Making use of the tools you've been learning about, it should be possible for you to create an algorithm that can iterate throughout an array and count all the existing items, even if they are repeated, as well as locating their positions within the array. See Activity 1, Searching for Multiple Occurrences in an Array in this chapter, where we challenge you to write such a program.

You can also transform objects of the java.util.Arrays class into strings with the Arrays.toString() method, as we saw at the beginning of this section, into a list with Arrays.asList() (we will see this in a later section, as well as in Example05) or into a set with Arrays.setAll().

Arrays and collections play important roles in software development. This section of the chapter dives into the differences between them as well as how they can be used together. If you search the internet for the relationship between these two constructs, most references you find will be focused on the differences, such as:

  • Arrays have fixed sizes, while collections have variable sizes.
  • Arrays can hold objects of any kind, but also primitives; collections cannot contain primitives.
  • Arrays will hold homogeneous elements (elements that are all the same nature), while collections can hold heterogeneous elements.
  • Arrays have no underlying data structure, while collections are implemented using standard structures.

If you know the amount of data you are going to be dealing with, arrays are the preferred tool, mainly because arrays perform better than lists or sets in such cases. However, there will be countless occasions when you don't know the amount of data you will be dealing with, which is where lists will be handy.

Also, arrays can be used to programmatically populate collections. We will be doing this throughout this chapter as a way of saving you the time of having to manually type all the data that will end up inside a collection, for example. The following example shows how to populate a set using an array:

import java.util.*;

public class Example05 {

    public static void main(String[] args) {

        Integer[] myArray = new Integer[] {3, 25, 2, 79, 2};

        Set mySet = new HashSet(Arrays.asList(myArray));

        System.out.println(mySet);

    }

}

In this program, there is an array of Integer used to initialize an object of the HashSet class, which is later printed out.

The outcome of this example is:

[2, 3, 25, 79]

Process finished with exit code 0

The previous code listing shows a couple of interesting things. First of all, you will notice that the output to the program is sorted; that is because the conversion of the array to a list using Arrays.asList() will make the dataset inherit the properties of a list, which means that it will be sorted. Also, since the data has been added to a set and sets do not include duplicates, duplicate number two is left out.

It is important to note that with collections, you can specify the type to be stored. As such, there would be a difference between the declaration in the previous example, where we displayed a generic declaration, and what follows. The type is declared here using the name given within angle brackets, <>. In this case, it is <Integer>. You could rewrite the instantiation of the object as follows:

Set<Integer> mySet = new HashSet<Integer>(Arrays.asList(myArray));

You will see that the result of executing the program will be the same.

Activity 1: Searching for Multiple Occurrences in an Array

Write a program that will search for multiple occurrences of a certain word in an array of strings, where each one of the objects is a single word. Use the following array, a famous quote by Frank Zappa, as a point of departure:

String[] text = {"So", "many", "books", "so", "little", "time"};

The word to search for is so. but you will have to consider that it shows up twice and that one instance is not in lowercase. As a hint, the method to compare two strings without looking at the specific casing of any of the letters in them is text1.compareToIgnoreCase(text2). To do so, perform the following steps:

  1. Create the text array.
  2. Create the variable that contains the word to be searched for: so
  3. Initialize the variable occurrence to -1.
  4. Create a for loop to iterate through the array to check for the occurrence.

That will give the following result:

Found query at: 0

Found query at: 3

Process finished with exit code 0

Note

The solution for this activity can be found on page 538.

主站蜘蛛池模板: 苗栗县| 天峨县| 长顺县| 三明市| 洛川县| 虹口区| 铜鼓县| 聊城市| 神农架林区| 阿拉尔市| 朔州市| 河曲县| 河曲县| 思南县| 潼南县| 新邵县| 和龙市| 新乐市| 淳化县| 科尔| 琼海市| 宿松县| 调兵山市| 多伦县| 迁安市| 定安县| 西盟| 奉节县| 会同县| 堆龙德庆县| 北碚区| 金湖县| 江城| 龙口市| 大埔区| 明溪县| 钟山县| 兰州市| 金寨县| 定安县| 六枝特区|