Friday, December 19, 2014

Binary Search



public class BinarySearchTest {
   
    public static void main(String[] args){
        int[] iarr = {1,3,5,7};
        int key = 5;
        int index = binarySearch(iarr,key);
        System.out.print(key+" is at index "+index);
    }

    private static int binarySearch(int[] iarr, int key) {
        int start = 0;
        int end = iarr.length-1;
        int mid = 0;
       
        while (start<=end){
            mid = (start+end)/2;
            if (key==iarr[mid]) {
                return mid;
            }
            else if (key<iarr[mid]){
                end = mid -1;
            }
            else if (key>iarr[mid]){
                start = mid+1;
            }

        }
        return -1;
    }

}

OUTPUT
5 is at index 2

Sunday, December 7, 2014

SortCollectionByComparator


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortCollectionByComparator {
   
   
public static void main(String[] args){
        List<Employee> empList = new ArrayList<Employee>();
        empList.add(new Employee("John",10));
        empList.add(new Employee("Alex",20));
        empList.add(new Employee("Mark",30));
       
        Collections.sort(empList,new SortEmpByNameComparator());
        for (Employee emp: empList){
            System.out.println(emp.getEmpName()+" "+emp.getEmpId());
        }
    }

}




public class Employee {
    private String empName;
    private Integer empId;

    public Employee() {
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }
   
    public Employee(String empName, Integer empId){
        super();
        this.setEmpName(empName);
        this.setEmpId(empId);
       
    }
}



import java.util.Comparator;

public class SortEmpByNameComparator implements Comparator<Employee> {

    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getEmpName().compareTo(emp2.getEmpName());
    }

}

OUTPUT
Alex 20
John 10
Mark 30


Tuesday, December 2, 2014

Sort HashMap on Value


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class MapSortByValue {
   
    public static void main(String[] args){
       
        Map map = new HashMap();
        map.put("a", 1);
        map.put("c", 3);
        map.put("b", 2);
       
        Set set = map.entrySet();
        List list = new ArrayList(set); // convert set to list
       
        // before sorting
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
       
        Collections.sort(list, new Comparator(){

            @Override
            public int compare(Object o1, Object o2) {
                Map.Entry<String, Integer> entry1 = (Map.Entry<String, Integer>) o1;
                Map.Entry<String, Integer> entry2 = (Map.Entry<String, Integer>) o2;
                return (entry1.getValue()).compareTo(entry2.getValue());
            }
        });
       
        // after sorting
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
}

Sunday, November 9, 2014

Arrays.sort(fruits, Fruit.FruitNameComparator) - Fruit static object FruitNameComparator



import java.util.Arrays;

public class ComparatorTest {
   
    public static void main(String[] args){
        Fruit fruit1 = new Fruit("banana",1);
        Fruit fruit2 = new Fruit("apple",2);
        Fruit fruit3 = new Fruit("orange",3);
        Fruit[] fruits = {fruit1, fruit2, fruit3};
        

        // we can write comparator based on properties
        Arrays.sort(fruits,Fruit.FruitNameComparator);
       
        for (Fruit fruit: fruits){
            System.out.println(fruit.getName());
        }
    }

}



import java.util.Comparator;

public class Fruit implements Comparable{
    public static final Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>(){

        @Override
        public int compare(Fruit fruit1, Fruit fruit2) {
            // fruit1.getName() is String, String.compareTo
            // String, Integer, Double all have compareTo()

            return fruit1.getName().compareTo(fruit2.getName());
        }
       
       
    };
    public Fruit(String name, int quantity) {
        super();
        this.name = name;
        this.quantity = quantity;
    }
   
    String name;
    int quantity;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
   
    // comparable means this object is comparable so it can compareTo other object
    @Override
    public int compareTo(Object compareFruit) {
        int compareFruitQuantity = ((Fruit)compareFruit).getQuantity();
        //ascending order
        return this.getQuantity() - compareFruitQuantity;
    }
   

}


OUTPUT
apple
banana
orange

Arrays.sort(Fruit) - Fruit needs to implement Comparable

Comparable is java.lang.Comparable
Comparator is java.util.Comparator

Comparable means this object is Comparable, it can compareTo other object
Comparator means tool can compare two objects, so it has method compare(object1, object2)

Comparable compare based on single property 
Comparator could compare based on multiple properties


import java.util.Arrays;

public class ComparableTest {
   
    public static void main(String[] args){
        Fruit fruit1 = new Fruit("banana",1);
        Fruit fruit2 = new Fruit("apple",2);
        Fruit fruit3 = new Fruit("orange",3);
        Fruit[] fruits = {fruit1,fruit2,fruit3};
       
        Arrays.sort(fruits);
       
        for (Fruit fruit:fruits){
            System.out.println(fruit.getName());
        }
    }

}

public class Fruit implements Comparable{
    public Fruit(String name, int quantity) {
        super();
        this.name = name;
        this.quantity = quantity;
    }
   
    String name;
    int quantity;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
   
    // comparable means this object is comparable so it can compareTo other object
    @Override
    public int compareTo(Object compareFruit) {
        int compareFruitQuantity = ((Fruit)compareFruit).getQuantity();
        //ascending order
        return this.getQuantity() - compareFruitQuantity;
    }
   

}


OUTPUT
banana
apple
orange

Sort ArrayList using Collections.sort


import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class SortArrayListTest {
   
    public static void main(String[] args){
        List list = new ArrayList();
        list.add("banana");
        list.add("apple");
        list.add("orange");
       
        Collections.sort(list);
       
        Iterator it = list.listIterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }

}


OUTPUT
apple
banana
orange

Sort Array using Arrays.sort


import java.util.Arrays;

public class SortArrayTest {
    public static void main(String[] args){
        String[] sa = {"banana","apple","orange"};
        Arrays.sort(sa);
       
        for (String s:sa){
            System.out.println(s);
        }
    }

}

OUTPUT
apple
banana
orange

Deep Copy

// deep copy, in clone() it creates a new object

public class DeepCopyTest {
   
    public static void main(String[] args) throws CloneNotSupportedException{
        Student student = new Student("Jet","Chinese"); // create student object
        Student student2 = student.clone(); // deep copy a new object student2
        System.out.println("student name="+student2.getName()+" subject="+student2.getSubject().getName());// print out this new object student2
        student.setName("Tom"); // change original object value
        student.getSubject().setName("English");
        System.out.println("student name="+student2.getName()+" subject="+student2.getSubject().getName()); // print out this new object value. it's changed.
               
    }

}



public class Student implements Cloneable{

    private String name;
    private Subject subject;
   
    public Student(String studentName, String subjectName) {
        this.name = studentName;
        this.subject = new Subject(subjectName);
    }

    @Override
    public Student clone() throws CloneNotSupportedException {
        Student student = new Student(name,subject.getName());
        return student ;
    }

    public String getName() {
        return this.name;
    }

    public Subject getSubject() {
        return this.subject;
    }

    public void setName(String studentName) {
        this.name = studentName;
    }

}

package deepcopy;

public class Subject {
    private String name;
   
    public Subject(String subjectName) {
        this.name = subjectName;
    }

    public String getName() {
        return name;
    }

    public void setName(String subjectName) {
            this.name = subjectName;
    }


}
OUTPUT



student name=Jet subject=Chinese
student name=Jet subject=Chinese

Friday, November 7, 2014

StringBuilder.insert - insert a string at position


public class InsertTest {
   public static void main(String[] args){
    StringBuilder sb = new StringBuilder("abcd");
    sb.insert(sb.indexOf("b"),"word");// insert word at position of b
   
    System.out.println(sb.toString());
   }

}

OUTPUT:
awordbcd

Tuesday, November 4, 2014

Shallow Copy


cloned object has own copy for primitive member but for object member, it will be shared with original object

http://www.jusfortechies.com/java/core-java/deepcopy_and_shallowcopy.php 

public class ShallowCopyTest {
   
    public static void main(String[] args) throws CloneNotSupportedException{
       
        Student stud = new Student("Jet","English");
        Student stud2 = (Student) stud.clone();
        System.out.println("student name="+stud2.getName()+" subject="+stud2.getSubject().getName());
        stud.setName("Tom");
        stud.getSubject().setName("Chinese");
        System.out.println("after original object is updated, cloned student name="+stud2.getName()+" subject="+stud2.getSubject().getName());
    }

}



public class Student implements Cloneable{

    private String name;
    private Subject subject;
   
    public Student(String studentName, String subjectName) {
        this.name = studentName;
        this.subject = new Subject(subjectName);
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public String getName() {
        return this.name;
    }

    public Subject getSubject() {
        return this.subject;
    }

    public void setName(String studentName) {
        this.name = studentName;
    }

}


Wednesday, October 29, 2014

Use BufferedReader to read a file


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class BufferedReaderTest {
   
    public static void main(String[] args) throws Exception{
        String fileName = "c:\\tmp\\test.txt";
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        while ((line = br.readLine())!=null){
            System.out.println("line="+line);
           
        }
        br.close();
        fr.close();
    }

}

Tuesday, October 28, 2014

Use BufferedWriter write to a file


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class BufferedWriterTest {
   
    public static void main(String[] args) throws IOException{
        String fileName = "C:\\tmp\\test.txt";
        File file = new File(fileName);    // File needs fileName
        FileWriter fw =  new FileWriter(file);    // so here use Writer implementing class - FileWriter
        BufferedWriter bw = new BufferedWriter(fw); //Writer can not be initialized b/c it's abstract class
        try {
            bw.write("this is my test file");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            bw.close();    // when close, the content can be written to the file
            fw.close();
        }

       
    }

}

Sunday, October 26, 2014

Collections.synchronizedMap when map is used in thread


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


// HashMap is not synchronized

public class MapTest {
    public static void main(String[] args){
        Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
        map.put("1", "a");
        map.put("2", "b");
        map.put("3", "c");
       
        for (Map.Entry<String, String> entry:map.entrySet()){
           
            System.out.println("key="+entry.getKey()+" value="+entry.getValue());
           
        }
       
    }

}


OUTPUT:
key=3 value=c
key=2 value=b
key=1 value=a

Sunday, October 12, 2014

Reverse Number


// how to write program: 
// give an example
// identify number by variable
// convert to program
// verify program by example

// if number to reverse is 123
// 12 3     0x10+3
// 1   2     3x10+2
// 0   1     32x10+1

public class ReverseNumberTest {
   
    public int reverseNumber(int number){
       
        int reverse = 0;
        while (number!=0){
            reverse = reverse*10 + number % 10;
            number = number / 10;

        }
       
        return reverse;
    }
   
    public static void main(String[] args){
        ReverseNumberTest rnt = new ReverseNumberTest();
        System.out.println("reverse number="+rnt.reverseNumber(123));
    }

}

Thursday, October 9, 2014

Reverse String (recursive)


public class ReverseStringTest {
   
    public String reverseString(String str){
       
        // str.substring(0,2) returns index of 0 and 1 of str
        return (str.length()==1? str: str.charAt(str.length()-1) + reverseString(str.substring(0,str.length()-1)));
       
    }
   
    public static void main(String[] args){
        ReverseStringTest rst = new ReverseStringTest();
        System.out.println(rst.reverseString("abcd"));
    }

}


OUTPUT:
dcba

Tuesday, October 7, 2014

ArrayList Loop (for, Iterator, ListIterator)


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

// Iterator vs ListIterator
// 1. Iterator traverse List and Set; ListIterator traverse List
// 2. Iterator can go next; ListIterator can go next and previous
// 3. Iterator can not get Index; ListIterator can get Index
// 4. Iterator can NOT add item when traverse; ListIterator can add when traverse
// 5. Iterator can NOT replace item when traverse; ListIterator can replace when traverse


public class ArrayListTest {
   
    public static void main(String[] args){
       
        List<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
        list.add("C");
       
        // use enhanced for to loop
        for (String str : list){
            System.out.println(str);
        }
       
        // use Iterator to loop
        Iterator it = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
       
        // use ListIterator to loop
        ListIterator li = list.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
               
    }

}


OUTPUT:

A
B
C
A
B
C
A
B
C

Sunday, October 5, 2014

java.lang.Math.random() and java.util.Random


import java.util.Random;

public class RandomTest {
   
    public static void main(String[] args){
       
        // 1) java.util.Random to generate random number
        Random random = new Random(1000); // 1000 is seed
        for (int i = 0; i<3; i++){
            System.out.println(random.nextInt()); // generates same random number because of seed is fixed
        }
       
        // 2) java.lang.Math.random() to generate random number
        for (int i=0; i<3; i++){
            System.out.println(Math.random()); // random double between 0 and 1, 0 is inclusive
        }
    }

}


OUTPUT:

-1244746321   (same)
1060493871    (same) 
-1826063944   (same)
0.22284876712156954   (different)
0.19407514115469882   (different)
0.2939945031187672     (different)

Thursday, October 2, 2014

Loop Map using Map.Entry in map.entrySet()


import java.util.HashMap;
import java.util.Map;

public class MapEntryTest {
   
    public static void main(String[] args){
       
        Map<String, String > map = new HashMap<String, String>();
       
        //initialize map
        map.put("1", "a");
        map.put("2", "b");
        map.put("3", "c");

        // entry in entrySet
        for (Map.Entry<String, String> entry : map.entrySet()){
            System.out.println("key="+entry.getKey()+" value="+entry.getValue());
        }
    }

}


OUTPUT:
key=3 value=c
key=2 value=b
key=1 value=a

HashMap


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FindDuplicateInString {
   
    public void findDuplicateInString(String str){
        char[] chars = str.toCharArray();
        Map<Character,Integer> map = new HashMap<Character,Integer>();
       
        // constructs map
        for (char ch : chars){
            if (map.containsKey(ch)){
                map.put(ch, map.get(ch)+1);
            }else{
                map.put(ch,1);
            }
        }
       
        // print out duplicate char
        Set<Character> keys = map.keySet();
        for (Character key : keys){
            if (map.get(key)>1){
                System.out.println("duplicate char: "+key);
            }
        }
       
       
    }
   
    public static void main(String[] args){
        FindDuplicateInString duplicate = new FindDuplicateInString();
        duplicate.findDuplicateInString("java");
    }

}

OUTPUT:
duplicate char: a

ListIterator


import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorTest {
   
    public static void main(String[] args){
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        ListIterator<Integer> li = list.listIterator();
       
        while (li.hasNext()){
            System.out.println(li.next());
        }
       
        while (li.hasPrevious()){
            System.out.println(li.previous());
        }
       
    }

}
OUTPUT:
1
2
3
3
2
1

Monday, September 22, 2014

count=count++

// count=count++;
// step 1: JVM copy count value to temp 
// step 2: count incremented by 1
// step 3: assign temp to count, count reset to 0

public class SelfIncrementTest {
   
    public static void main(String[] args){
       
        int count = 0;
        for (int i=0;i<10;i++){
            count = count++;
        }
       
        System.out.println(count);
    }

}

OUTPUT
0

varargs



public class VarargsTest {
   
    public void methodA(String str, Integer... is){
       
        System.out.println("first methodA called");
       
    }
   
    public void methodA(String str, String... strs){
        System.out.println("second methodA called");
       
    }
   
    public static void main(String[] args){
       
        VarargsTest vt = new VarargsTest();
        vt.methodA("USA", 0);
        vt.methodA("USA",  "People");
        //vt.methodA("USA"); // compile error. compiler does not know which methodA to invoke
        //vt.methodA("USA",  null); // compile error. null is not any type. compiler does not know which methodA to invoke
       
       
    }

}



OUTPUT
first methodA called
second methodA called

Ternary type must match


// data types in ternary must match

public class TernaryTest {
   
    public static void main(String[] args){
        int i = 80;
        String s1 = String.valueOf(i<90?90:100);
        String s2 = String.valueOf(i<90?90:100.0); // 90 converted to 90.0
       
        System.out.println("s1="+s1);
        System.out.println("s2="+s2);
    }

}

OUTPUT
s1=90
s2=90.0

Saturday, September 20, 2014

instanceof


import java.util.Date;

public class InstanceOfTest {
  
    // if no extend or implementation relationship between two objects, it will give compile error.
  
    public static void main(String[] args){
        boolean b = false;
      
        b = "a" instanceof String;
        System.out.println(b);
      
        b = new String() instanceof String;
        System.out.println(b);
      
        b = new Object() instanceof String; // object is not instanceof String
        System.out.println(b);
      
        //b = 'A' instanceof Character;
        // compile error. 'A' is simple variable and Character is object
      
        b = null instanceof String; // null is not instanceof any types
        System.out.println(b);
      
      
        String s = (String) null; // s is still null even after conversion
        System.out.println(s);
      
        b = (String) null instanceof String; // null is still null even after conversion
        System.out.println(b);
      
        //b = new Date() instanceof String;
        // compile error.
        // No extend or implementation relationship between Date and String so compile error.
    }

}



OUTPUT
true
true
false
false
null
false