Arrays class

In this article, we will discuss Arrays class – a utility class for Collection framework for inter-conversion between arrays and List, which has useful methods for

  • Sorting
  • Searching
  • Conversion to List
  • etc

 

Arrays:

  • All utility methods inside Arrays class are static
  • Methods can be invoked directly using class-name, without creating instance
  • This is mostly used for List; for inter-conversion between Arrays and List

 

Arrays method:

Arrays method Description
void sort(primitive[] pmt); here, primitive can be int, short, long, double, char, byte, float
Note: only natural ordering is possible for primitive types
void sort(Object[] object); any object implementing Comparable interface
void sort(Object[] o, Comparator c); to sort any object based on specified Comparator
void binarySearch(primitive[] pmt, primitive e); here, primitive can be int, short, long, double, char, byte, float

e –> element to be searched

void binarySearch(Object[] oArray, object obj); obj is the object searched from specified object array
void binarySearch(Object[]oArray, object obj Comparator c); obj is the object searched from specified object array
based on specified Comparator
List asList(Object[] oArray); Used to convert array into list object but actually a List reference not separate object

 

Advantages of Arrays :

  • It is used to store one or more element/objects of same-type
  • It can referred/accessed using single variable-name
  • Easily any element can be accessed using index-position
  • It can also be used to implement 2D matrices

Disadvantages of Arrays :

  • Arrays size/length is fixed, which we need assign while creating/initializing
  • Due to its fixed, it doesn’t increases when more elements need to be added or doesn’t get shrinks when elements are removed
  • So, we all must know in advance about Arrays size, while creating/initializing itself
  • Since Arrays stores elements in contagious location therefore it is time-consuming activity to insert/add or remove/delete elements
  • If we under-utilised is more than its capacity, then memory gets wasted
  • Similarly, it isn’t flexible to add/insert more elements

 

References:

 

Happy Coding !!
Happy Learning !!

Sorting Arrays using Comparable and Comparator
How to shuffle elements of ArrayList