Collections List


List Interface:
  • List allows Duplicate Elements.
  • List having index.
  • List allows n number of null values.
  • List will display Insertion order with index.
  • List having classes like :
  • Vector
  • ArrayList
  • LinkedList


Introduction to the Java List Interface

The List interface in Java forms part of the core of the Java Collections Framework. It offers access to an ordered list of objects. In contrast with sets, lists allow duplicates as well as maintain insertion order. This makes lists perfect for sequences. When sequence matters, the List interface in Java is useful for modeling things like user input, products returned from a database query, or steps in a workflow.

In this guide, you'll find the List interface and its implementing classes: ArrayList, LinkedList, Vector, and Stack. We will examine their performance characteristics, use cases, and best practices to help you select the right one for any given project.

Key Characteristics of the List Interface

  • Accepted Elements: Elements maintain their order of insertion.
  • Index-based access: Retrieve, add, or remove elements by position.
  • Duplicates allowed: Lists can contain the same item more than once.
  • Null-Safe: Most implementations of List allow null values.

Classes that Implement the List Interface

1. ArrayList

  • What It Is: A resizable array implementation.
  • When to Use: Ideal for read-heavy, random access operations.
  • Performance:
    • Access: O(1) (fast for get() and set()).
    • Insert/Delete: O(n) (because shifting items is required).

Example:

List<String> fruits = new ArrayList<>();
fruits.add("Apple");  
fruits.add("Banana");  
System.out.println(fruits.get(0)); // Output: Apple  

2. LinkedList

  • What It Is: A doubly-linked list implementation.
  • When to Use: Ideal for frequent insertions and deletions.
  • Performance:
    • Access: O(n) (poor for random access).
    • Insert/Delete: O(1) (when modifying head or tail).

Example:

List<Integer> numbers = new LinkedList<>();
numbers.add(10);  
numbers.addFirst(5); // Add at head  

3. Vector

  • What It Is: An array-based list that is thread-safe.
  • When to Use: In multi-threading environments (although ArrayList with explicit synchronization is preferred).
  • Disadvantage: Being synchronized makes it slower than ArrayList.

Example:

List<String> colors = new Vector<>();
colors.add("Red");  
colors.add("Blue");  

4. Stack

  • What It Is: A Vector subclass that implements LIFO (Last-In-First-Out).
  • Methods:push(), pop(), peek().
  • When to Use: For undo/redo operations, parsing expressions, and backtracking algorithms.

Example:

Stack<String> stack = new Stack<>();
stack.push("Task1");  
stack.push("Task2");  
System.out.println(stack.pop()); // Output: Task2  

ArrayList Vs. LinkedList Vs. Vector Vs. Stack

Class Underlying Data Thread-Safe? Use Cases
ArrayList Dynamic array No Read-heavy operations
LinkedList Doubly linked list No Frequent insertions/deletions
Vector Array Yes Legacy applications
Stack Array (Vector) Yes LIFO-based operations

Best Practices When Using Java Lists

  1. Choose the Right Implementation:
    • Default to ArrayList for most use cases.
    • Use LinkedList for queue-like behavior (addFirst(),removeLast()).
  2. Avoid Synchronized Classes: Use Collections.synchronizedList() with ArrayList instead of Vector.
  3. Preallocate Capacity: Initialize larger ArrayLists with a capacity to reduce resizing overhead.
  4. Leverage Java 8+ Features: Use streams and lambda functions for filtering, mapping, and sorting.

Frequently Asked Questions on Java Lists

Question 1: When should I use ArrayList as opposed to LinkedList?

  • ArrayList: Best for random access and read-heavy operations.
  • LinkedList: Best for frequent insertions/deletions.

Question 2: Is Vector still relevant in modern-day Java?

  • Vector is largely outdated. Use CopyOnWriteArrayList or java.util.concurrent classes for thread safety.

Question 3: How do I convert a List to an array?

  • Use String[] array = list.toArray(new String[0]);

4: How do I sort a List?

  • Use Collections.sort(list) or list.sort(Comparator).


By mastering the Java List interface and its implementations, you can write efficient, scalable code. Whether you are building high-performance applications with ArrayLists, managing complex workflows with LinkedLists, or using Vectors for legacy applications, understanding their strengths and weaknesses is key.

Found this guide helpful? Share with a friend!

Stay tuned for more tutorials on Java Collections, Spring Boot, and System Design.

Keywords: Java List interface, ArrayList vs LinkedList, Vector and Stack in Java, Java Collections tutorial, List implementations in Java.


Jsp life cycle


     
  • jsp engine controls the life cycle of jsp
  • Jsp life cycle is described by three life cycle methods and six life cycle phases

Jsp life cycle methods :

  • jspInit()
  • _jspService()
  • jspDestroy()
Jsp Life Cycle

  • Jspinit() method is invoked when JSP page is initialized.
  • The _jspService() method corresponds to the body of the jsp page.
  • This method is defined automatically by the JSp container and should never be defined y the JSP page author.

Jsp Life cycle Phases: 

  • Translation phase
  • Compilation phase
  • Instantiation phase
  • initialization phase
  • Servicing phase
  • Destruction phase

Jsp Life Cycle methods




  • Jsp engine calls jspInit() method only once during the initialization phase of a jsp.
  • similarly during destruction phase jsp engine calls jspDestory() method only once
  • For each client request Jsp container calls _jspService() method once.

Jsp Translation phase:

  • When client request comes for a jsp for the first time , jsp engine makes a full read of the jsp verifies the syntactical corectness of the jsp elements and converts code into a servlet source code .
  • The process of JSP engine translating jsp into servlet nothing but translation phase of JSP.
  • Therefore , we say that Jsp development is another style of development  asking container to develop the servlet is nothing but JSP developement
  • Container generated servlet class is also known as page implementation class.

Jsp Compilation phase:

  • The process of jsp engine compiling the page implementation class is nothing but compilation phase of jsp.
  • Jsp engine uses JASPER compiler to compile the container generated servlet class source code.
  • In the life of the Jsp Translation and compilation happens only once unless jsp source code modified.

Jsp Instantiation phase:

  • Container creating the instance of generated servelt class is nothing but instantialtion phase of jsp
  • actually now we have a servelt object.
  • Servlet engine loads user user defined servlet class file from secondary memory into
    primary memory dynamically

    class c= class.forName("name");
    c.newInstance();
  • Servlet engine creates the instance of loaded servlet class.
  • Servlet engine uses the following piece of code to load the servlet clas  dynamically to instantiate it.
    Class c= class.forName("Servlet class name");
    c.newInstance();


Initialization:

  • Servlet engine creates servletConfig object
  • Servlet engine calls the init() method on the servlet instance by supplying servletconfig object
    as argument.
  • Once init method completely executed servlet is ready to serve the client request.

Servicing : 

  • Servlet engine creates servlet request and servlet response object based on the web server
    provided client information.
  • Servlet engine calls service method on the servlet instance by supplying two object reference as arguments
  • Once service method is completely executed , client request is served and request-response cycle is complete.
  • Within the service method request object is used to capture the user input
  • Response object is used to build the dynamic page and hand over the same to the web server

Destruction:

  • Destruction phase of servlet represents servlet being removed from use by container

Jsp scripting elements

  • Jsp scripting elements are used to embed jva code in to the jsp.
  • Jsp scripting elements are three types
    1. Declaration
    2. Expression
    3. Scriplet

Jsp Declaration:

  • Jsp declaration is one of the three scripting elements.
  • it is used to embed java code into the jsp
  • A Jsp declration starts with "<%!" and ends with "%>".
  • <%! int a%>.
  • Instance variables, instance methods, static methods can be declared and defined in ajsp declaration.
  • During translation time of jsp they became members of container generated servlate/page implementation class.

Jsp Expression:

  • Jsp Expression is one of the three scripting elements.
  • it is used to embed java code into the js.
  • A jsp expression starts with "<%=" and ends with "%>".
  • <%=a+b%>
  • within a Jsp expression only one java expression that too without semicolon is placed.
  • When Jsp expression is evaluated two thing will happen in the backend
    1. Java expression is evaluated
    2. The result is sent to the browser stream.
  •  we can have any number of jsp expressions in ajsp.
  • During translation phase each java expression of a jsp expression is placed in into _jspService()
    method of page implemented class


Jsp Scriplet:

  • Jsp scriplet is one of the three scripting elements.
  • it is used to embed java code into the js.
  • A jsp scriplet starts with "<%" and ends with "%>".
  • <% java code%>
  • To serve the client request what ever java code required that is placed in servlet.
  • In servlet programming whatever code we write in the service() method of user defined servlet all that code can be placed in a jsp scriplet.
  • During the translation phase java code placed in the scriplet is written in to _jspService() method of page implementation class.
  • in jsp we can have any number of scriplets.

JSP in java

  • Java Server Pages is a java based web technology
  • Jsp ia J2EE technology.
  • JSP is a specification for web container manufacturers.
  • JSP is an API.
  • JSP is aweb component
  • JSP is a dynamic web resource of a web application.
  • JSP is web server side piece of code that extends functionality of web server.
  • Jsp engine is a software written in java technology according to JSP specification.

General duties of JSP:

  • Capturing user input
  • communicating with DB
  • Processing the data
  • Producing the response

JSP API:

  • Javax.ei
  • javax.servlet.jsp
  • javax.servlet.jsp.el
  • javax.servlet.jsp.targext

Interfaces present in javax.servlet.jsp:

  • HttpJspPage
  • JspApplicationContext
  • JspPage

  Classes present in javax.servlet.jsp:

  • ErroeData
  • JspContext
  • JspEngineInfo
  • JspFactory
  • JspWriter
  • PageContext
check below links for more details

Write a program to sort object using comparator?

Here I am taking class Employee:

package com.instanceofjava;
public class Employee {
 int id;
 String name;
 public Employee(int id, String name) {
  this.id=id;
  this.name=name;
 }
  public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

Here I am implementing Comparator:
class MyEmpComp implements Comparator<Employee >{

    @Override
    public int compare(Employee e1, Employee e2) {
        if(e1.getName() < e2.getName()){
            return 1;
        } else {
            return -1;
        }
    }

}




Here I am taking another class Main.Here I am adding objects to the My list
package com.oops;
import java.util.ArrayList;  
import java.util.Collections;
import java.util.Iterator;
import java.io.*;  
  
class Main{  
public static void main(String args[]){  
  
ArrayList al=new ArrayList();  
al.add(new Employee(101,"Indhu"));  
al.add(new Employee(106,"Sindhu"));  
al.add(new Employee(105,"Swathi"));  
  
Collections.sort(al,MyEmpComp );  
Iterator itr=al.iterator();  
while(itr.hasNext()){  
Employee st=(Employee)itr.next();  
System.out.println(st.id +" "+st.name );  
  }  
}  
}  



Output:
Indhu
Swathi
Sindhu



ServletContext


  • We can deploy multiple web applications in a servlet container.
  • Each web application contains its own resources in a separate  environment. This environment called ad Web Application context or ServletContext.
  • The resources belongs to the one web application context are not available to the other web application context.
  • A Servlet context contains zero or more number of servlets. For every servlet object the container creates separate servletConfig object.
  • ServletContext is an interface. this interface implemented by the container by the container provider.
  • The implemented class allows all servlets in the web application to communicate with the container.
  • We can store common data into this application and also we can share that data even after request response objects deletion in the memory.

ServletContext

 Configure Context parameters in web.xml file

ServletContext


Methods of ServletContext interface:

  1. public String getInitParameter(String name): Returns a String containing a value of the method context-wide initialization  parameter, or null if if parameter does not exist.
  2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as enumeration of string objects , or empty enumeration if context has no initialization parameters.
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the servlet container attribute with the given name , or null if there is no attribute by that name.
  5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.
  6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
  7. public int getMajorVersion(): Returns the major version of the Java Servlet API that is servlet container supports.
  8. public int getMinorVersion(): Returns the minor version of the Java Servlet API that is servlet container supports.
  9. public void log(Java.lang.String msg): Writes specified message to a servlet log file, usually an event log.

How to get the object of ServletContext interface:

       ServletContext application=getServletConfig().getServletContext();   
          String driverName=application.getInitParameter("name");  


Select Menu