Online Java Compiler By
JavaTpoint.com
import java.util.*; public class CollectionsBinarySearchExample5 { public static void main(String[] args) { //Create a list List
list = new ArrayList
(); list.add(new Domain(10, "www.JavaTpoint.com")); list.add(new Domain(20, "www.sssit.com")); list.add(new Domain(30, "www.hindi100.com")); Comparator
c = new Comparator
() { public int compare(Domain u1, Domain u2) { return u1.getId().compareTo(u2.getId()); } }; /* Searching a domain with key value 10. To search we create an object of domain with key 10. */ int index = Collections.binarySearch(list, new Domain(10, null), c); System.out.println("Available at index: " + index); //Searching an item with key 5 index = Collections.binarySearch(list, new Domain(5, null), c); System.out.println("Found at index: " +index); } } //user-defined class to store domains with id and url class Domain { private int id; private String url; // Constructor public Domain(int id, String url) { this.id = id; this.url = url; } public Integer getId() { return Integer.valueOf(id); } }
Output