java.util Summary 4 (Arrays, List, ListIterator)

This time:

--Arrays class --List interface --ListIterator interface

Arrays class

This class is a class that can manipulate arrays in various ways. The characteristic of this class is that all methods are static, so when using the methods of the Arrays class, be sure to add Arrays. (For example, ʻArrays.asList (...), described later. Must be used unless (like Arrays.addAll (...) `).

asList method

A method defined in this class (Arrays class) that converts an array to a ** fixed length list **.

For example, with a simple code

AsListSample1.java


import java.util.Arrays;
import java.util.List;

public class AsListSample1 {
	
	public static void main(String[] args){
		String[] strs = {"a","b","c"};
		
		List<String> list = Arrays.asList(strs);
		System.out.println(list);
	}
}

When you execute

[a, b, c]

And the result comes out. However, note that the following code will return an exception.

AsListSample2.java


import java.util.Arrays;
import java.util.List;

public class AsListSample2 {
	
	public static void main(String[] args){
		String[] strs = {"a","b","c"};
		
		List<String> list = Arrays.asList(strs);
		list.add("d");
		
		System.out.println(list);
	}
}
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at com.test.java.util.AsListSample2.main(AsListSample2.java:12)

This is because the asList method returns ** as a fixed length list ** as I wrote earlier, so converting to a List type does not mean that the length will be variable, but the length of the list will change. Then an exception is thrown. Therefore, after converting to List type, it is not possible to add or remove.

However, if you use this alone, you will not feel like using it so much at a cost, but the solution is to return it to the list as ** variable length in advance with the following code.

AsListSample3.java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AsListSample3 {
	
	public static void main(String[] args){
		String[] strs = {"a","b","c"};
		
		List<String> list = new ArrayList<String>(Arrays.asList(strs));
		list.add("d");
		
		System.out.println(list);
	}
}

Then

[a, b, c, d]

It returns without throwing an exception properly. By the way, although primitive types such as numbers do not throw exceptions, they cannot be used in lists etc. (There is a method), so be careful.

copyOf method

A method defined in this class that copies a specified array to another array up to the specified length. At that time, the length of the copy destination array can be changed.

In the first argument, you can specify the array type boolean, byte, char, double, float, int, long, short, as the array you want to copy the object, and in the second argument you can specify the length of the copy destination array. .. Only the array type of the object has a third argument, and a class (subclass) that inherits the copy destination class type (superclass) can be specified and specified as a new class array type.

It ’s a simple example,

CopyOfSample.java


import java.util.Arrays;

public class CopyOfSample {
	
	public static void main(String[] args){
		String[] strs = {"a","b","c"};
		String[] copyStrshort = Arrays.copyOf(strs,2);
		String[] copyStrs = Arrays.copyOf(strs,6);
		
		for(int i = 0; i < copyStrs.length; i++){
			
			if(copyStrshort.length > i){
				System.out.println("Of the array copyStrshort" + i + "The second is →" + strs[i]);
			}
			
			System.out.println("Of the array copyStrs" + i + "The second is →" + copyStrs[i]);
		}
	}
}

The execution result is

The 0th of the array copyStrshort is → a
The 0th of the array copyStrs is → a
The first of the array copyStrshort is → b
The first of the array copyStrs is → b
The second of the array copyStrs is → c
The third of the array copyStrs is → null
The fourth of the array copyStrs is → null
The fifth of the array copyStrs is → null

Will be.

here, The array copied by the copyOf method is automatically processed even if the copy destination array is longer than the copy source array or shorter than the original array. If it is short, elements up to the specified length can be put in the copy destination array. If the copy destination array is longer than the original array, the initial value of that type is automatically entered in each of the remaining element parts.

For the time being, the initial values that are automatically entered are as follows:

Mold Value that fits in the surplus element
boolean false
byte 0
char '\u000'
double 0.0 (0d)
float 0.0 (0f)
int 0
long 0 (0L)
short 0
object null

List interface

List familiar with List <> list = new ArrayList <> (). Writing like this is done with the intention of giving it some extensibility after this (for example, when you want to use a method that is only available in List type), or it increases readability. However, if you use it in the sense that it will not be extensibility after this, it is not good to make it a List type. Classes that implement this interface (ArrayList, LinkedList, etc.) are generally defined within this List interface.

add method, addAll method

Methods defined in the Collection interface. A method that adds an element to a list. The addAll method is a method that adds the specified collection to the list as a whole. It is also possible to specify the position to put the element at the beginning within the range that does not exceed the index of the list in the first argument.

An example of adding a new element after putting all the elements of the array in the list,

ListSample.java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListSample {

	public static void main(String[] args) {
		String[] strs = {"a","b","c"};
		List<String> list = new ArrayList<String>();
		
		list.addAll(Arrays.asList(strs));
		
		System.out.println("First add " + list);
		
		list.add("d");
		list.add(2,"h");
		
		System.out.println("Second add " + list);
	}
}

Result is

First add [a, b, c]
Second add [a, b, h, c, d]

toArray method

Methods defined in the Collection interface. A method that converts a list to an array. asList method Something like the opposite method. You can specify the array type you want to return as an argument.

As a continuation of the code in the previous example,

ListSample.java (continued)


System.out.println("Convert as Object: ");
		
for(Object item : list.toArray()){
	System.out.println(item);
}
		
System.out.println();
System.out.println("Convert as String: ");
	
for(String item : list.toArray(new String[list.size()])){
	System.out.println(item);
}

Result is

Convert as Object: 
a
b
h
c
d

Convert as String: 
a
b
h
c
d

The first example is a simple and simple example, and the second example is an example of passing as a String type, although the number of characters is a little large because it was unpleasant to output the list that has as an element of String as an Object.

listIterator method

A method that returns a List type as a ListIterator type (described later). When an argument is specified (index number), the specified argument is first called as an index in the next method of ListIterator type.

ListIterator interface

An interface that provides an iterator for lists. Has no current element. Taking advantage of this, it is possible to search not only from the forward direction but also from the reverse direction.

hasNext, nextIndex, next methods

Other than the nextIndex method, it is defined in the Iterator interface, and the nextIndex method is defined in this interface.

The hasNext method is a method that returns true when there is an element in the next index. The nextIndex method is a method that returns the index of the element returned when the next method is called. The next method returns the next element and moves the cursor further forward.

As a simple example

ListIteratorSample.java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorSample {

	public static void main(String[] args) {
		String[] strs = {"a","b","c","d"};
		List<String> list = new ArrayList<String>(Arrays.asList(strs));
		ListIterator<String> listIterator = list.listIterator();
		
		while(listIterator.hasNext()){
			System.out.println("index" + listIterator.nextIndex() + "The element of" + listIterator.next());
		}
	}
}

Result is

The element with index 0 is a
The element at index 1 is b
Index 2 element is c
The element of index 3 is d

end

I wrote that the ListIterator interface allows reverse search, but that's another opportunity ...

Recommended Posts

java.util Summary 4 (Arrays, List, ListIterator)
java.util Summary 3 (HashTable, Enumeration)