Java Tutorials 21-30/56

Java Tutorials


  1. Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.

  • Simple Java Hashtable Example
  • HeapSort
  • InsertionSort
  • ArrayList using Iterator Example
  • Iterate through a Collection using Java Iterator Example
  • Java Boolean Example
  • Linear Search
  • Simple Java LinkedHashMap example
  • LinkedHashSet Example
  • LinkedList Example

Name Code

Simple Java Hashtable Example

       public class SimpleHashtableExample
   {
     public static void main(String[] args)
     {
       //create object of Hashtable
       Hashtable ht = new Hashtable();
      
       /*
       Add key value pair to Hashtable using
       Object put(Object key, Object value) method of Java Hashtable class,
       where key and value both are objects
       and can not be null.
       put method returns Object which is either the value previously tied
       to the key or null if no value mapped to the key.
       */
      
       ht.put("One", new Integer(1));
       ht.put("Two", new Integer(2));
      
       /*
       Please note that put method accepts Objects. Java Primitive values CAN NOT
       be added directly to Hashtable. It must be converted to corrosponding
       wrapper class first.
       */
      
       //retrieve value using Object get(Object key) method of Java Hashtable class
       Object obj = ht.get("One");
       System.out.println(obj);
      
       /*
       Please note that the return type of get method is Object. The value must
       be casted to the original class.
       */
     }
   } 

HeapSort

         public class HeapSort
   {
     private static int heapSize; //this will help us to stop sorting list numbers that are already sorted.
     /**
     * Sorts the given list in place.
     * Worst Case Performance O(nlogn)
     * Best Case Performance O(nlogn)
     * Average Case Performance O(nlogn)
     * @param A - list that needs to be sorted.
     */
     public void sortNumbers(int[] A)
     {
       HeapSort(A);
     }
     /**
     * Read sortNumbers method description.
     * @param A - list that needs to be sorted.
     */
     private void HeapSort(int[] A)
     {
       heapSize = A.length; //we need to sort all the list so heapSize == A.length
       BuildMaxHeap(A); //first we build max heap
       //now we have the biggest element in the heap on the top
       //we will exchange it with the last element in the list
       //reduce heapSize so this (biggest) element wont be sorted anymore
       //and we will call MaxHeapify once again to get new biggest element on the top
       //and once again we place it at the current end of the list, we do it all the way
       //til we will have only one element left in the heap (which will be the lowest number)
       //this way our array will get sorted, from smallest (at the start of the list) to biggest (at the end of the list).
       for (int i = A.length-1; i>0; i--)
       {
         //exchange biggest number with the current last one
         int temp = A[0];
         A[0] = A[i];
         A[i] = temp;
         //reduce the heap size
         heapSize--;
         //find new biggest
         MaxHeapify(A,0);
       }
     }
     /**
     * Builds MaxHeap (runs in linear time so: O(n) )
     * if n = amount of numbers in the list, then n/2 = amount of leaves (nodes that have no children)
     * We need to call MaxHeapify from bottom and up, but we can skip all leaves so we start at index = n/2 and go up.
     * @param A - list that we will build MaxHeap of.
     */
     private void BuildMaxHeap(int[] A)
     {
       for(int i = A.length/2-1;i>=0;i--)
       {
         MaxHeapify(A, i);
       }
     }
     /**
     * Takes O(logn) or we can also say that if subtree with root at index i has height of h
     * then running time of algorithm is O(h) (note that a binary tree with n elements has height = logn)
     * Sorts the array at the given index so that subtree meets heap requirements.
     * @param A array list
     * @param i index of the root of subtree that might be smaller than its children.
     */
     private void MaxHeapify(int[] A, int i)
     {
       int l = Left(i); //lets find left child of the given index.
       int r = Right(i);//lets find right child of the given index.
       int max;
       if (l < heapSize)
       {
         //lets check if left child is an existing child
         //if it is an existing child
         if (A[l] > A[i])
         {
           //if left child is bigger than parent
           max = l; //left child becomes maximum
         }
         else
         {
           max = i; //otherwise parent is maximum
         }
       }
       else
       {
         //if this index does not have left child
         max = i;
       }
       if (r < heapSize)
       {
         //lets check if the right child is an existing child
         //if it is existing child
         if(A[r] > A[max])
         {
           //if right child is bigger than our current maximum
           max = r; //right child becomes our new maximum
         }
       }
       if (max != i)
       {
         //if our parent is not maximum
         //we need to swap max with parent
         int temp = A[i];
         A[i] = A[max];
         A[max] = temp;
         //at the end we need to run MinHeapify on the child that was just swapped
         //and see if it is supposed to go even further down the list
         MaxHeapify(A, max);
       }
     }
     /**
     * Returns Left child index of the given parent index.
     * @param i - parent index.
     * @return - index of parents left child.
     */
     private int Left(int i)
     {
       return 2 * i;
     }
     /**
     * Returns Right child index of the given parent index.
     * @param i - parent index.
     * @return - index of parents right child.
     */
     private int Right(int i)
     {
       return (2 * i) + 1;
     }
     /**
     * Just for testing purposes.
     */
     public static void main(String[] args)
     {
       int[] list = {156,344,54,546,767,23,34,64,234,654,234,
65,234,65,87,3,5,76,24,2,3,7,9,5,34,32,
4525,345,0};

       HeapSort hs = new HeapSort();
       hs.sortNumbers(list);
       for (int i = 0;i < list.length;i++)
       {
         System.out.println(list[i]);
       }
     }
    
   }       

InsertionSort

      public class InsertionSort
   {
     /**
     * Sorts the given list in place.
     * Worst Case Performance O(n^2)
     * Best Case Performance O(n)
     * Average Case Performance O(n^2)
     * @param list - int array that you want to sort.
     */
     public static void sortNumbers(int[] list)
     {
       //go through the list of the numbers, starting with number two (we say that number one is already sorted)
       for (int i=1; i< list.length -1; i++)
       {
         //store the value of the number we are dealing with (because it's place can be taken by other bigger numbers)
         int value = list[i];
         //define j (its a pointer to the already sorted list, starting at the largest number - back of the sorted list)
         int j = i-1;
         //as long as value is lower than the number in sorted list and we are still in the list
         while (j >= 0 && list[j] > value)
         {
           // we are going to move the higher number(from the sorted list) one step to the right (so it will make space for the current value number - witch is lower)
           list[j+1] = list[j];
           //and we move our pointer in the list to next place - lower number
           j--;
         }
         //once we come to the right spot, we insert our value number in there and start with next i value.
         list[j+1] = value;
       }
     }
   } 

ArrayList using Iterator Example

        public class IterateThroughArrayListUsingIteratorExample
   {
     public static void main(String[] args)
     {
       //create an ArrayList object
       ArrayList arrayList = new ArrayList();
      
       //Add elements to Arraylist
       arrayList.add("1");
       arrayList.add("2");
       arrayList.add("3");
       arrayList.add("4");
       arrayList.add("5");
      
       //get an Iterator object for ArrayList using iterator() method.
       Iterator itr = arrayList.iterator();
      
       //use hasNext() and next() methods of Iterator to iterate through the elements
       System.out.println("Iterating through ArrayList elements...");
       while(itr.hasNext())
         System.out.println(itr.next());
     }
   } 

Iterate through a Collection using Java Iterator Example

       public class JavaIteratorExample
   {
     public static void main(String[] args)
     {
       //create an ArrayList object
       ArrayList aList = new ArrayList();
      
       //populate ArrayList object
       aList.add("1");
       aList.add("2");
       aList.add("3");
       aList.add("4");
       aList.add("5");
      
       /*
       Get Iterator object by invoking iterator method of collection.
       Iterator provides hasNext() method which returns true if has more
       elements. next() method returns the element in iteration.
       */
       Iterator itr = aList.iterator();
      
       //iterate through the ArrayList values using Iterator's hasNext and next methods
       while(itr.hasNext())
         System.out.println(itr.next());
      
       /*
       Please note that next method may throw a java.util.NoSuchElementException
       if iteration has no more elements.
       */
      
     }
   } 

Java Boolean Example

      public class JavaBooleanExample
   {
     public static void main(String[] args)
     {
       //Create an Boolean object using one the below given ways
       //1. Create an Boolean object from boolean value
       Boolean blnObj1 = new Boolean(true);
      
       /*
       2. Create an Boolean object from String. It creates a Boolean object
       representing true if the string is not null and equals to true. Otherwise
       it creates Boolean object representing false.
       */
       Boolean blnObj2 = new Boolean("false");
      
       //print value of Boolean objects
       System.out.println(blnObj1);
       System.out.println(blnObj2);
     }
   } 

Linear Search

      public class LinearSearch
   {
     public int find(final int[] data, final int key)
     {
       for (int i = 0; i < data.length; ++i)
       {
         if (data[i] > key)
           return -1;
         else if (data[i] == key)
           return i;
       }
       return -1;
     }
     public static void main(String[] args)
     {
       final int arr[] = new int[10];
       System.out.println("Enter 10 numbers");
       Scanner input = new Scanner(System.in);
       for (int i = 0; i < arr.length; i++)
       {
         arr[i] = input.nextInt();
       }
       LinearSearch search = new LinearSearch();
       System.out.print("Enter the element to search: ");
       int num=input.nextInt();
       int n = search.find(arr, num);
       if ((n >= 0) && (n < arr.length))
       {
         System.out.println("Found at index: " + n);
       }
       else
       {
         System.out.println("Not Found");
       }
     }
   }   

Simple Java LinkedHashMap example

       public class JavaLinkedHashMapExample
   {
     public static void main(String[] args)
     {
       //create object of LinkedHashMap
       LinkedHashMap lHashMap = new LinkedHashMap();
      
       /*
       Add key value pair to LinkedHashMap using
       Object put(Object key, Object value) method of Java LinkedHashMap class,
       where key and value both are objects
       put method returns Object which is either the value previously tied
       to the key or null if no value mapped to the key.
       */
      
       lHashMap.put("One", new Integer(1));
       lHashMap.put("Two", new Integer(2));
      
       /*
       Please note that put method accepts Objects. Java Primitive values CAN NOT
       be added directly to LinkedHashMap. It must be converted to corrosponding
       wrapper class first.
       */
      
       //retrieve value using Object get(Object key) method of Java LinkedHashMap class
       Object obj = lHashMap.get("One");
       System.out.println(obj);
      
       /*
       Please note that the return type of get method is an Object. The value must
       be casted to the original class.
       */
      
     }
   } 

LinkedHashSet Example

       public class SimpleLinkedHashSetExample
   {
     public static void main(String[] args)
     {
       //create object of LinkedHashSet
       LinkedHashSet lhashSet = new LinkedHashSet();
      
       /*
       Add an Object to LinkedHashSet using
       boolean add(Object obj) method of Java LinkedHashSet class.
       This method adds an element to LinkedHashSet if it is not
       already present in LinkedHashSet.
       It returns true if the element was added to LinkedHashSet, false otherwise.
       */
      
       lhashSet.add(new Integer("1"));
       lhashSet.add(new Integer("2"));
       lhashSet.add(new Integer("3"));
      
       /*
       Please note that add method accepts Objects. Java Primitive values CAN NOT
       be added directly to LinkedHashSet. It must be converted to corrosponding
       wrapper class first.
       */
      
       System.out.println("LinkedHashSet contains.." + lhashSet);
     }
   } 

LinkedList Example

      public class SimpleJavaLinkedListExample
   {
     public static void main(String[] args)
     {
      
       //create LinkedList object
       LinkedList lList = new LinkedList();
      
       //add elements to LinkedList
       lList.add("1");
       lList.add("2");
       lList.add("3");
       lList.add("4");
       lList.add("5");
      
       /*
       * Please note that primitive values can not be added into LinkedList
       * directly. They must be converted to their corrosponding wrapper class.
       */
      
       System.out.println("LinkedList contains : " + lList);
     }
   } 
Java Tutorials 21-30/56 Java Tutorials 21-30/56 Reviewed by Abdul hanan on 08:19:00 Rating: 5
Powered by Blogger.