How to remove last element in a array and store it in same Array

 
import java.util.Arrays;

public class SimpleArray 
{
  public static void main(String[] args) 
  {
    String[] arrNames1 = {"Mugil", "Mani", "Vinu", "Shivaji", "Raman"};
    String[] arrNames2 = new String[arrNames1.length-1]; 
		
    for(int i=0;i<arrNames1.length-1;i++)
      arrNames2[i] = arrNames1[i];
		
    arrNames1 = arrNames2.clone();
		
    for (int i = 0; i < arrNames1.length; i++) 
      System.out.println(arrNames1[i]);		
  }
}

MySQL TIMEDIFF function runs well in MySQL but with JDBC it generate SQL Exception.
The problem is that the TIMEDIFF(expr1,expr2) function returns expr1 – expr2 expressed as a time value.

This value is handled by java.sql.Time. But TIMEDIFF( , ) may return (for example) 12:45:00 or 40:30:01 as the case may be. For first value it works but for the second value it is not a proper time value according to java.sql.Time, hence the exception.

To get rid of this problem is to use concat as follows

CONCAT('',TIMEDIFF(expr1,expr2))

Now the returned value will be a String instead of a Time and which prevents JDBC from parsing it.

Set

  • Set prevents duplication.The common use of set is to check for duplication
  • Since its is helpful for lookups for duplicate value HashSet provides an optimized implementation
  • If you want the result to be sorted use TreeSet instead of HashSet
Posted in Set.

Why ArrayList Faster than LinkedList during Random Access?
ArrayList has direct references to every element in the list, so it can get the n-th element in constant time. LinkedList has to traverse the list from the beginning to get to the n-th element.

Why LinkedList faster than ArrayList during Insertion/Deletion?
ArrayList is slower because it needs to copy part of the array in order to remove the slot that has become free. If the deletion is done using the ListIterator.remove() API, LinkedList just has to manipulate a couple of references; if the deletion is done by value or by index, LinkedList has to potentially scan the entire list first to find the element(s) to be deleted.

  • LinkedList takes constant-time insertions or removals. I can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.
  • ArrayLists allows random access, so I can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if I add more elements than the capacity of the underlying array, a new array (twice the size) is allocated, and the old array is copied to the new one, so adding to an ArrayList is O(n) in the worst case but constant on average.
  • Iterating over both the Types is equally cheap.
  • If you have large lists, the memory usage is different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored

When should I use LinkedList?

  • When you need efficient removal in between elements or at the start.
  • When you don’t need random access to elements, but can live with iterating over them one by one

When should I use ArrayList?

  • When you need random access to elements (“get the nth. element”)
  • When you don’t need to remove elements from between others. It’s possible but it’s slower since the internal backing-up array needs to be reallocated.
  • Adding elements is amortized constant time (meaning every once in a while, you pay some performance, but overall adding is instantly done)
Operation Linked List Array List
Access O(n) O(1)
Insertion Access time + O(1) Access time + O(n)
Deletion Access time + O(1) Access time + O(n)

When you are simple moving through List but you are not modifying the List object foreach is more efficient.In case you want to perform operations on each element of list individually taking out the element in such case use Iterator.

List<Fruits> arrFruits = new ArrayList<Fruits>();
Iterator<Fruits> itFrt = arrFruits.iterator();

while(itFrt.hasNext())
{
 Fruits frt = itFrt.next();
 System.out.println(frt);
}

ListIterator

  • While using Iterator in particular to List using a ListIterator is more powerful over Iterator.
  • ListIterator is bidirectional
  • It also keep track of Indexes of next and previous elements
  • It can replace last element it visited using set method
 List<fruits> arrFruits     = fruits.arrayList(5);
 ListIterator<fruits> itFrt = arrFruits.listIterator();

 while(itFrt.hasNext())
 {
   System.out.println(it.next()); 
   System.out.println(it.nextIndex()); 
   System.out.println(it.previousIndex()); 
 }
  • List maintains elements in Particular Sequence.
  • Two types of List 1.ArrayList and 2.LinkedList
  • ArrayList is faster while accessing elements but slower while Insertion and Deletion
  • LinkedList is slow in random access but faster during insertion and deletion

Operations in ArrayList

class Fruits
{	
  String Name = "Fruit";
}

class Apple extends Fruits
{	
 public Apple()
 {
   Name = "Apple";
 }
}

class Orange extends Fruits
{	
 public Orange()
 {
  Name = "Orange";
 }
}

class Mango extends Fruits
{	
 public Mango()
 {
  Name = "Mango";
 }
}

Adding Element – List.add()

List<Fruits> arrFruits = new ArrayList<Fruits>();
Fruits objApple  = new Apple();
Fruits objMango  = new Mango();
arrFruits.add(objApple);
arrFruits.add(objMango);

Removing Element – List.remove()

arrFruits.remove(objApple);

Removing by Index – List.remove()

arrFruits.remove(1);

Index of Element – List.indexOf()

arrFruits.indexOf(objMango);

Index of Element – List.indexOf()

arrFruits.indexOf(objMango);

SubList – List.subList(StartPOS, EndPOS)

List<Fruits> arrNewFruits = arrFruits.subList(0,2);

containsAll – NewList.containsAll(OrgList)

 arrNewFruits.containsAll(arrFruits);

set Value at Index

 arrNewFruits.set(1, new Orange());

removeAll

 arrFruits.removeAll(arrFruits);

addAll

 arrFruits.addAll(arrNewFruits);

retainAll – set Intersection Operation
retainAll performs set Interscetion Operation by taking Two ArrayList. It Retains Boolean true if intersection finds element false otherwise.

List<Integer> arrNums1 = new ArrayList<Integer>();
arrNums1.add(1);
arrNums1.add(2);
arrNums1.add(3);
		
List<Integer> arrNums2 = new ArrayList<Integer>();
arrNums2.add(1);

System.out.println(arrNums1.retainAll(arrNums2));
System.out.println(arrNums1);

Consider the Following Example

 Collection<Integer> coll = new ArrayList<Integer>();

 coll.addAll(Arrays.asList(1,2,3,4,5));

In the above addAll the addition takes place in following steps as Below
1.varargs+autoboxing creates Integer[]
2.Arrays.asList creates a List backed by the array
3.addAll iterates over a Collection using Iterator

Now consider the Below Code

 Collection<Integer> coll = new ArrayList<Integer>();

 coll.addAll(coll, 1,2,3,4,5);

1.varargs+autoboxing creates Integer[]
2.addAll iterates over an array (instead of an Iterable)

We can see now that b) may be faster because:

Arrays.asList call is skipped, i.e. no intermediary List is created.
Since the elements are given in an array, iterating over them may be faster than using Iterator.

Need for Generics
Pre Java 5 Containers allows to insert an incorrect type into a Container.Consider a container you need to store Apple objects in it.The code for scenario is as shown below

public class Generics1
{
  public static void main(String[] args)
  {
    List arrFruits = new ArrayList();
    arrFruits.add(new Apple());
    arrFruits.add(new Mango());
		
    for (Object object : arrFruits)
    {
     System.out.println(((Apple)object).Name);
    }
  }
}

class Apple
{	
  String Name = "Ooty";
}

class Mango
{	
  String Name = "Malgova";
}

Now the above code compiles Perfectly fine.But when you try to run the code you will encounter a problem in casting to Apple class as you added Mango object in to arrFruits.The code compiles without error since every thing you add using add method into ArrayList gets converted to Object before it get Stored.

By Using generics you are preventing the addition of wrong type of Object into the container as Below.

public class Generics1
{	
 public static void main(String[] args)
 {
   List<Apple> arrFruits = new ArrayList<Apple>();
   arrFruits.add(new Apple());
   arrFruits.add(new Mango()); //Compile Time Error
		
   for (Apple object : arrFruits)
   {
     System.out.println(object.Name);
   }
  }
}

You can also see there is no need for Casting while using Generics.

You can also store Subtype of Parent class in Generics as Below

 
public class Generics1
{	
 public static void main(String[] args)
 {
   ArrayList<Fruits> arrFruits = new ArrayList<Fruits>();
   arrFruits.add(new Fruits());
   arrFruits.add(new Apple());
   arrFruits.add(new Orange());
   arrFruits.add(new Mango());
	
   for (Fruits object : arrFruits)
   {
     System.out.println(object.Name);
   }
 }
}

class Fruits
{	
  String Name = "I am Fruit";
}

class Apple extends Fruits
{	
  public Apple()
  {
    Name = "I am Apple";
  }
}

class Orange extends Fruits
{	
  public Orange()
  {
    Name = "I am Orange";
  }
}

class Mango extends Fruits
{	
   public Mango()
   {
     Name = "I am Mango";
   }
}

The Containers can be Broadly Classified in to Two types.

1.Collection
2.Map

The Collection includes the following
1.ArrayList
2.LinkedList
3.HashSet
4.TreeSet
5.LinkedHashSet

The Map includes the following
1.HashMap
2.TreeMap
3.LinkedHashMap

Boxing
Boxing is the process of converting the Primitive type to Reference type

byte to Byte
int to Integer
double to Double
char to Character

Unboxing
Unboxing is the process of converting the Reference type to Primitive type

Byte to byte
Integer to int
Double to double

Consider the Following example

List arrAges = new ArrayList();
arrAges.add(25);
int n = arrAges.get(0);

is equivalent to

List arrAges = new ArrayList();
arrAges.add(new Integer(25));
int n = arrAges.get(0).intValue();

Boxing an int or short value between -128 and 127, a Char value between ‘\u0000’ and ‘\u007f’, byte and boolean

Consider the following example

Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer d = a + b;
System.out.println(c == d);

Output
true
The output is true because the value comparison is taking place instead of object comparison.Boxed values between -128 to 127 are cached. Boxing uses Integer.valueOf method, which uses the cache. Values outside the range are not cached and always created as a new instance. Since your values fall into the cached range, values are equal using == operator.

This is What happening when values boxed are between -128 to 127

Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer c = Integer.valueOf(5);
Integer d = Integer.valueOf(a.intValue() + b.intValue());

Output
true

when you try to add integers which are outside the range as one below

Integer a = 300;
Integer b = 200;
Integer c = 500;
Integer d = a + b;
System.out.println(c == d);

Output
false

How to Check Content in List with String

 List arrNums  = new ArrayList();
 arrNums.add(2);
 arrNums.add(3.14);
 assert arrNums.toString().equals("[2,3.14]");

List is not a Subtype of List
List is a Subtype of Collection

Doesn’t Works

 List ints = Arrays.asList(1,2);
 List nums = ints;  //Not Ok as you try to Assign List to List

The above doesn’t works as you try to add List to List

Works

 List ints1 = Arrays.asList(1,2);
 Collection nums = ints1;

Addition of Subtypes in Supertype in generics is Allowed as Below

List nums = new ArrayList();
List ints2 = Arrays.asList(1,2);
List ints3 = Arrays.asList(3.1,2.15);

nums.add(3.15);
nums.addAll(ints2);
nums.addAll(ints3);

Assignment of Subtype to Supertype is not allowed

 List nums = new ArrayList();
 List ints = Arrays.asList(1,2);
 nums.addAll(ints); //Allowed
 nums = ints; //Not Allowed

Assignment of List to List is Not Allowed

Use extends wildcard when you get values out of Structure and use super wildcard when you put values into structure

 List<? extends Integer> arrNums = new ArrayList();
 List arrInts           = new ArrayList();
 arrInts.add(1);
 arrInts.add(2);
 arrInts.add(3);

 arrNums.addAll(arrInts); //Not Allowed since wildcard is extends(get)

 

 List<? super Integer> arrNums = new ArrayList();
 List arrInts         = new ArrayList();
 arrInts.add(1);
 arrInts.add(2);
 arrInts.add(3);

 arrNums.addAll(arrInts); //Allowed since wildcard is super(put)

 


	
protected void doGet(HttpServletRequest request, 
                     HttpServletResponse response) 
                     throws ServletException, IOException 
{	
   int lngCookieSet    = 0;
   String strCookieVal = "";
   String cookieName   = "Name";
	
   Cookie[] cookies = request.getCookies();
		
   if(cookies != null && cookies.length > 0)
   {
      for(int i=0;i<cookies.length;i++)
      {
        if(cookieName.equals(cookies[i].getName()))
        {
          lngCookieSet = 1;
          strCookieVal = cookies[i].getValue();
        }
      }
   }	
		
   if(lngCookieSet == 1)
   {
     PrintWriter prw = response.getWriter();	
     prw.print(strCookieVal);
   }
   else
   {
     Cookie cook = new Cookie("Name", "Mugil");
     cook.setMaxAge(24*60*60*365);//1 Year
     response.addCookie(cook);	
   }
}

Notes
1. check cookies != null otherwise the compiler will generate null pointer exception
2. The new Cookie constructor will take Cookie Name and Value as Parameter.
3. The addCookie Will add cookie to response Header to set cookie on Client Side