List and ArrayList Example:

List and ArrayList Example: Hi friends this is my first post on core java. I think you know the basics of Collections. I am not explaining basics here. When i am learning java I saw so  many sites are giving examples only on Collections to add integer or string or float. Little bit sites only giving example on adding objects and retrieving  then from Collections. this is my first example using java.util.List and java.util.Arraylist. i am not explaining anything about this example.I think you can understand by seeing this example.

 

 

the usage of this example is understanding List and ArrayList and contains method. we are adding employee to a list and avoiding duplicates while adding to list by overriding equals method. and retrieving all employees and displaying them from List. have any questions contact me or post a comment below.

Employee.java;

package com.jagadeesh.domain;

public interface Employee {

public Integer getId();

public void setId(Integer id);

public String getFirstName();

public void setFirstName(String firstName);

public String getLastName();

public void setLastName(String lastName);

public void setEmail(String email);

public String getEmail();

public int getPriority();

public void setPriority(int priority);

public String getDesignation();

public void setDesignation(String designation);

public String toDisplayString();

}

EmployeeImpl.java

package com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO

implements Employee {

private static final long serialVersionUID = 5058287999709032283L;

private Integer id;

private String firstName;

private String lastName;

private String email;

private int priority;

private String designation;

@Override

public Integer getId() {

return id;

}

@Override

public void setId(Integer id) {

this.id = id;

}

@Override

public String getFirstName() {

return firstName;

}

@Override

public void setFirstName(String firstName) {

this.firstName = firstName;

}

@Override

public String getLastName() {

return lastName;

}

@Override

public void setLastName(String lastName) {

this.lastName = lastName;

}

@Override

public String getEmail() {

return email;

}

@Override

public void setEmail(String email) {

this.email = email;

}

@Override

public int getPriority() {

return priority;

}

@Override

public void setPriority(int priority) {

this.priority = priority;

}

@Override

public String getDesignation() {

return designation;

}

@Override

public void setDesignation(String designation) {

if ("CEO".equalsIgnoreCase(designation)) {

setPriority(1);

} else if ("MD".equalsIgnoreCase(designation)) {

setPriority(2);

} else if ("HR".equalsIgnoreCase(designation)) {

setPriority(3);

} else {

setPriority(4);

}

this.designation = designation;

}

@Override

public String toString() {

StringBuffer buffer = new StringBuffer();

buffer.append("EmployeeImpl [id=");

buffer.append(id);

buffer.append(", firstName=");

buffer.append(firstName);

buffer.append(", lastName=");

buffer.append(lastName);

buffer.append(", email=");

buffer.append(email);

buffer.append(", priority=");

buffer.append(priority);

buffer.append(", designation=");

buffer.append(designation);

buffer.append("]");

return buffer.toString();

}

@Override

public boolean equals(Object object) {

if (object == null)

return false;

if (object == this)

return true;

if (this.getClass() != object.getClass())

return false;

Employee employee = (Employee) object;

if (this.id == employee.getId()

this.firstName.equalsIgnoreCase(employee.getFirstName())

this.lastName.equalsIgnoreCase(employee.getLastName())

this.email.equalsIgnoreCase(employee.getEmail())

this.designation.equalsIgnoreCase(employee.getDesignation()))

return true;

return false;

}

@Override

public String toDisplayString() {

StringBuffer buffer = new StringBuffer();

buffer.append(this.getId());

buffer.append("\t");

buffer.append(this.getFirstName());

buffer.append("\t");

buffer.append(this.getLastName());

buffer.append("\t");

buffer.append(this.getEmail());

buffer.append("\t");

buffer.append(this.getDesignation());

return buffer.toString();

}

}

</pre>

<b>EmployeeService.java</b>

<pre class="brush:java">package com.jagadeesh.service;

import java.util.List;

import com.jagadeesh.domain.Employee;

public interface EmployeeService {

List<Employee> getAll();

void addEmployee(Employee employee);

}

</pre>

<b>EmployeeServiceImpl.java</b>

<pre class="brush:java">package com.jagadeesh.service.impl;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {

private List<Employee> employees = new ArrayList<Employee>();

@Override

public List<Employee> getAll() {

List<Employee> employees = new ArrayList<Employee>(this.employees);

return Collections.unmodifiableList(employees);

}

@Override

public void addEmployee(Employee employee) {

if (employees.contains(employee)) {

System.out.println("Employee already exists");

} else {

this.employees.add(employee);

}

}

}

EmployeeIO.java

package com.jagadeesh.utils;

import java.util.List;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.domain.impl.EmployeeImpl;

public class EmployeeIO {

public static Employee read() {

Employee employee = new EmployeeImpl();

employee.setId(KeyBoard.readInt("Enter Id :"));

employee.setFirstName(KeyBoard.read("Enter First Name :"));

employee.setLastName(KeyBoard.read("Enter Last Name :"));

employee.setEmail(KeyBoard.read("Enter Email :"));

employee.setDesignation(KeyBoard.read("Enter Designation :"));

return employee;

}

public static void out(List<Employee> employees) {

StringBuilder builder = new StringBuilder();

builder.append("Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n");

for (int i = 0; i < employees.size(); i++) {

builder.append(employees.get(i).toDisplayString());

builder.append("\n");

}

System.out.println(builder);

}

}

KeyBoard.java

package com.jagadeesh.utils;

import java.util.Scanner;

public class KeyBoard {

public static int readInt(String message) {

System.out.print(message);

Scanner scanner = new Scanner(System.in);

try {

int number = Integer.parseInt(scanner.next());

return number;

}

catch(NumberFormatException e) {

System.out.println("Invalid Number");

return readInt(message);

}

}

public static String read(String message) {

System.out.print(message);

Scanner scanner = new Scanner(System.in);

return scanner.nextLine();

}

}

EmployeeMain.java

package com.jagadeesh.main;

import com.jagadeesh.domain.Employee;

import com.jagadeesh.service.EmployeeService;

import com.jagadeesh.service.impl.EmployeeServiceImpl;

import com.jagadeesh.utils.EmployeeIO;

import com.jagadeesh.utils.KeyBoard;

public class EmployeeMain {

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

int option = 1;

EmployeeService empService = new EmployeeServiceImpl();

do {

Employee employee = EmployeeIO.read();

empService.addEmployee(employee);

option = KeyBoard.readInt(

"Do you want add another employee(1/0) :");

} while(option == 1);

System.out.println("Reading from List");

EmployeeIO.out(empService.getAll());

}

}

Out put of the program

Enter Id :1

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Do you want add another employee(1/0) :1

Enter Id :2

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Do you want add another employee(1/0) :1

Enter Id :1

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Employee already exists

Do you want add another employee(1/0) :testing invalid option

Invalid Number

Do you want add another employee(1/0) :1

Enter Id :3

Enter First Name :jagadeesh

Enter Last Name :kumar

Enter Email :[email protected]

Enter Designation :developer

Do you want add another employee(1/0) :0

Reading from List

Id First Name Last Name EmailĀ  Designation

1 jagadeesh kumar [email protected] developer
2 jagadeesh kumar [email protected] developer
3 jagadeesh kumar [email protected] developer

Pin it

Builder pattern in Java

Builder falls under the type of creational pattern category. Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.

Figure: – Builder concept

To understand what we mean by construction and representation lets take the example of the below ā€˜Tea preparationā€™ sequence.

You can see from the figure ā€˜Tea preparationā€™ from the same preparation steps we can get three representation of teaā€™s (i.e. Tea with out sugar, tea with sugar / milk and tea with out milk).

Figure: – Tea preparation

Now letā€™s take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either ā€˜PDFā€™ or ā€˜EXCELā€™ format. Figure ā€˜Request a reportā€™ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.

Ā 

Figure: – Request a report

Now letā€™s take a different view of the problem as shown in figure ā€˜Different Viewā€™. The same flow defined in ā€˜Request a reportā€™ is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.

Figure: – Different View

We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

ā€¢Ā Builder: – Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
ā€¢Ā Director: – Director takes those individual processes from the builder and defines the sequence to build the product.
ā€¢Ā Product: – Product is the final object which is produced from the builder and director coordination.

First letā€™s have a look at the builder class hierarchy. We have a abstract class called as ā€˜ReportBuilderā€™ from which custom builders like ā€˜ReportPDFā€™ builder and ā€˜ReportEXCELā€™ builder will be built.

Ā 

Figure: – Builder class hierarchy

Figure ā€˜Builder classes in actual codeā€™ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for ā€˜PDFā€™ (ReportPDF) and other for ā€˜EXCELā€™ (ReportExcel). These two custom builders define there own process according to the report type.

Figure: – Builder classes in actual code

Now letā€™s understand how director will work. Class ā€˜clsDirectorā€™ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ā€˜Director in actionā€™ shows how the method ā€˜MakeReportā€™ calls the individual process to generate the report product by PDF or EXCEL.

The third component in the builder is the product which is nothing but the report class in this case.

Ā 

Figure: – The report class

Now letā€™s take a top view of the builder project. Figure ā€˜Client,builder,director and productā€™ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.

Figure: – Client, builder, director and productĀ 

The output is something like this. We can see two report types displayed with their headers according to the builder.

Figure: – Final output of builder

 

 

Source -http://ashishkhandelwal.arkutil.com/?p=1076

Pin it

Three main categories of design patterns?


There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.
Creational Patterns

ā€¢Ā Abstract Factory:- Creates an instance of several families of classes
ā€¢Ā Builder: – Separates object construction from its representation
ā€¢Ā Factory Method:- Creates an instance of several derived classes
ā€¢Ā Prototype:- A fully initialized instance to be copied or cloned
ā€¢Ā Singleton:- A class in which only a single instance can exist

Note: – The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States).
Structural Patterns

ā€¢Ā Adapter:-Match interfaces of different classes.
ā€¢Ā Bridge:-Separates an objectā€™s abstraction from its implementation.
ā€¢Ā Composite:-A tree structure of simple and composite objects.
ā€¢Ā Decorator:-Add responsibilities to objects dynamically.
ā€¢Ā FaƧade:-A single class that represents an entire subsystem.
ā€¢Ā Flyweight:-A fine-grained instance used for efficient sharing.
ā€¢Ā Proxy:-An object representing another object.

Note : To remember structural pattern best is (ABCDFFP)
Behavioral Patterns

ā€¢Ā Mediator:-Defines simplified communication between classes.
ā€¢Ā Memento:-Capture and restore an object’s internal state.
ā€¢Ā Interpreter:- A way to include language elements in a program.
ā€¢Ā Iterator:-Sequentially access the elements of a collection.
ā€¢Ā Chain of Resp: – A way of passing a request between a chain of objects.
ā€¢Ā Command:-Encapsulate a command request as an object.
ā€¢Ā State:-Alter an object’s behavior when its state changes.
ā€¢Ā Strategy:-Encapsulates an algorithm inside a class.
ā€¢Ā Observer: – A way of notifying change to a number of classes.
ā€¢Ā Template Method:-Defer the exact steps of an algorithm to a subclass.
ā€¢Ā Visitor:-Defines a new operation to a class without change.

Note: – Just remember Music……. 2 MICS On TV (MMIICCSSOTV).