Importance of deepToString() and asList() methods in Java?


An array is an object that holds a fixed number of values of a single type in a contiguous memory location. Both deepToString() and asList() methods are static methods of Arrays class. The deepToString() method converts multi-dimensional array to string and it checks if an array has the element as an array then it converts that array in the string format. The asList() creates a list with a fixed size, means that we cannot add an element by add() method in the returned list by Arrays.asList(). The asList() method acts as a bridge between an array and a list because the list returned by asList() method cannot extend the size.but can use all other methods of a list.

Syntax for Arrays.deepToString()

public static String deepToString(Object[] a)

Example

import java.util.Arrays;

public class DeepToStringTest {
   public static void main(String [] args){
      int[][] array = new int[][] {{1, 2, 3}, {11, 12, 13}, {21, 22,23}};
      System.out.println(Arrays.deepToString(array));
   }
}

Output

[[1, 2, 3], [11, 12, 13], [21, 22, 23]]


Syntax for Arrays.asList()

public static List asList(T... a)

Example

import java.util.Arrays;

public class AsListTest {
   public static void main(String[] args) {
      String[] strArray = {"Welcome", "to", "TutorialsPoint"};
      System.out.println(Arrays.asList(strArray));
   }
}

Output

[Welcome, to, TutorialsPoint]
raja
Published on 08-Aug-2019 08:57:02
Advertisements