Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is Arrays class in Java?

Searching elements of Arrays

 

Arrays class defines the following binary search methods.

All rules of Arrays class binary search method are exactly same as Collections class binary search methods.

  • What is Arrays class in Java?

package com.java4us; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; public class Test1 { public static void main(String args[]) throws IOException { int a[] = { 10, 20, 40, 50, 30, 70 }; Arrays.sort(a); System.out.println(Arrays.binarySearch(a, 20)); // index: 1 System.out.println(Arrays.binarySearch(a, 60)); // insertion point: -6 String s[] = { "a", "b", "y", "q", "d", "k" }; Arrays.sort(s); System.out.println(Arrays.binarySearch(s, "y")); // index: 5 System.out.println(Arrays.binarySearch(s, "c")); // insertion point: -3 Arrays.sort(s, new myComparator()); System.out.println(Arrays.binarySearch(s, "a", new myComparator())); //// index: 5 } } class myComparator implements Comparator { public int compare(Object obj1, Object obj2) { String s1 = obj1.toString(); String s2 = obj2.toString(); return s2.compareTo(s1); } }

Conversion of Array to List

Public static List asList(Object o) Strictly speaking this method won’t create an independent list object for the existing array we are getting List view.
  • By using array reference if we perform any change automatically the change will be reflected in the list, similarly by using List reference if we perform any change that change will be reflected automatically to the array.
  • By using List reference we can’t perform any operation which varies the size otherwise we will get RuntimeException saying unsupported operation exception.
  • By using List Reference we are not allowed to replace with heterogeneous objects otherwise we will get RuntimeException saying ArrayStoreException.
  • What is Arrays class in Java?
//Arrays in Java
package com.java4us; import java.io.IOException; import java.util.Arrays; import java.util.List; public class Test1 { public static void main(String args[]) throws IOException { String[] strings = { "Welcome", "To", "Java4us" }; List l = Arrays.asList(strings); System.out.println(l); strings[0] = "pleasant"; System.out.println(l); } }
  • What is Arrays class in Java?

Need for the Java-Arrays Class:
There are often times when loops are used to do some tasks on an array like:

  • Fill an array with a particular value.
  • Sort an Arrays.
  • Search in an Arrays.
  • And many more.

Tags:  , , , , , , , ,

(2) Comments

Leave a Reply

Your email address will not be published.