Translate

Friday, July 24, 2015

Java collections tutorial

The two most popular collections used in Java are List and Map. Both are generic interfaces. Java framework library provides many implementations of both these interfaces.

   The most popular implementation of List is the ArrayList class. ( If you are from the C# world, note that Arraylist in java has nothing to do with Arraylist in C#. ArrayList in java is strongly typed and more similar to List<T> in C#.).

The most popular implementation of Map in Java is the HashMap.



An example of List in java

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

public class Main {

    public static void main(String[] args) {

        List<Student> students = new ArrayList<Student>();

        Student student1 = new Student() {{
            setName("Jack");
            setCollege("MIT");
            setMajor("Computer Science");
            setSsn("123-45-5678");
        }};

        Student student2 = new Student() {{
            setName("Sandra");
            setCollege("Harvard");
            setMajor("Medicine");
            setSsn("999-45-5678");
        }};

        students.add(student1);
        students.add(student2); 

        for (Student s : students) {
            System.out.println(s.getName());
        }

    }
}

 
public class Student {

    private String name;
    private String college;
    private String major;
    private String ssn;

    public String getName() {
        return name;
    }

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

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public String getSsn() {
        return ssn;
    }

    public void setSsn(String ssn) {
        this.ssn = ssn;
    }
}


Note here that Lists are allowed to have duplicates. In the above example you can enter the same student object multiple times into the List.





An example of Map in java

You use a Map when you want to look up values by a key. For example you could store people's information in a Map and look them up by their Social Security number (key).  

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

public class Main {

    public static void main(String[] args) {

        Map<String, Student> students = new HashMap<String, Student>();

        Student student1 = new Student() {{
            setName("Jack");
            setCollege("MIT");
            setMajor("Computer Science");
            setSsn("123-45-5678");
        }};

        Student student2 = new Student() {{
            setName("Sandra");
            setCollege("Harvard");
            setMajor("Medicine");
            setSsn("999-45-5678");
        }};

        students.put(student1.getSsn(), student1);
        students.put(student2.getSsn(), student2);


        System.out.println(students.get("999-45-5678").getName());//Sandra
    }
}



Monday, July 20, 2015

Builder pattern tutorial Java (Beginners introduction to builder pattern)

The requirement

Suppose you need a Sandwich class which has 3 ingredients bread, cheese and meat. The requirement is you can pick any combination of these items. And once the Sandwich class is initialized, you shouldn't be able to change these ingredients. One easy way to achieve this is


public class Sandwich {

    private String bread;//immutable
    private String cheese;//immutable
    private String meat;//immutable

    public Sandwich(String bread, String cheese, String meat) {
        this.bread = bread;
        this.cheese = cheese;
        this.meat = meat;
    }

    public String getBread() {
        return bread;
    }

    public String getCheese() {
        return cheese;
    }


    public String getMeat() {
        return meat;
    }

}



public class Main {
   
public static void main(String[] args) {
        Sandwich mySandwich =
new Sandwich("ItalianBread", "Swiss", "");
    }
}

The above code doesn't let you change the ingredients once you initialize it, which meets our requirement at the same time you have to specify all the ingredients even if you don't need it. (We didn't want meat in our sandwich so we just passed an empty string for meat).


A more graceful code that uses builder pattern

A more graceful way of handling the above requirement is by using a builder pattern. In this pattern, we use a nested static class. 

public class Sandwich {
   
private String bread;// immutable
   
private String cheese;///immutable
   
private String meat;///immutable

   
public Sandwich(Builder builder) {
       
this.bread = builder.bread;
       
this.cheese = builder.cheese;
       
this.meat = builder.meat;
    }

   
public static class Builder {

       
private String bread;
       
private String cheese;
       
private String meat;

       
public Builder() {
        }

       
public Builder bread(String bread) {
           
this.bread = bread;
           
return this;//We are returning a reference to itself so that we can call other methods on it like cheese() meat() and so on
       
}

       
public Builder cheese(String cheese) {
           
this.cheese = cheese;
           
return this;
        }

       
public Builder meat(String bread) {
           
this.meat = meat;
           
return this;
        }

       
public Sandwich build() {
           
return new Sandwich(this
);
        }

    }


   
public String getBread() {
        
return bread;
    }

   
public String getCheese() {
       
return cheese;
    }

   
public String getMeat() {
       
return meat;
    }

}

public class Main {
    public static void main(String[] args) {
        Sandwich.Builder sandwichBuilder=new Sandwich.Builder();
        sandwichBuilder.bread("ItalianBread").cheese("swiss");
        Sandwich mySandwich=sandwichBuilder.build();
    }
}




Friday, July 10, 2015

Java InputStreamReader simple example

To  follow along go to a ascii to binary converter and get a binary array for your text.

The text I am using is
Hi
9

This text when converted to binary looks like this





















In the java program below these are things I will do

Create a byte array for my data
Create an InputStream object with the byte array
Use an InputStreamReader to interpret that InputStream data as ASCII data
Read the data in InputStreamReader with a BufferedReader


import java.io.*; 

public class Play {

    public static void main(String[] args) throws IOException {


        byte[] arrayOfBytes = new byte[]
                {
                        (byte) 0b01001000,

                        (byte) 0b01101001,

                        (byte) 0b00001101,

                        (byte) 0b00001010,

                        (byte) 0b00111001
                };

        InputStream is = new ByteArrayInputStream(arrayOfBytes);

        InputStreamReader isr = new InputStreamReader(is, "ASCII");

        BufferedReader br = new BufferedReader(isr);

        String line;

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

    }
}






Dont forget to put 0b as a prefix when inputting binary data into the byte array. 
































































You can also print out non ascii characters. You just need to change the setting of your IDE to allow that. In intelliJ this is done by changing File Encoding under your project settings





Here is an example that prints out 您好 (Hello in Chinese)