Tuesday, 1 April 2014

remove : Remove Element from the List

boolean remove(Object o)
    Removes the first occurrence of the specified element from this list. Returns true if the list change after performing the operation else false.


import java.util.*;
class ListRemove{
 public static void main(String args[]){
  List<String> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add("Hi");
  myList.add("How");
  myList.add("Are");
  myList.add("You");
  myList.add("How");
  
  System.out.println("Elements in the list are");
  System.out.println(myList+"\n");
  
  /* remove Element from list */
  System.out.println("Removing the element \"How\" from the list " + myList.remove("How"));
  
  System.out.println("Elements in the list After removing \"How\" ");
  System.out.println(myList +"\n");
  
  /* remove Element from list */
  System.out.println("Removing the element \"abcd\" from the list " + myList.remove("abcd"));
  
  System.out.println("Elements in the list After removing \"abcd\" ");
  System.out.println(myList+"\n");
 }
}

Output
Elements in the list are
[Hi, How, Are, You, How]

Removing the element "How" from the list true
Elements in the list After removing "How"
[Hi, Are, You, How]

Removing the element "abcd" from the list false
Elements in the list After removing "abcd"
[Hi, Are, You, How]

1. remove method throws ClassCastException if the type of the specified element is incompatible with this list

2. remove method throws NullPointerException if the specified element is null and this list does not permit null elements

3. remove method throws UnsupportedOperationException if the remove operation is not supported by this list




Prevoius                                                 Next                                                 Home

Add Element to the List

boolean add(E e)
    Appends the specified element to the end of this list.

import java.util.*;
class ListAdd{
 public static void main(String args[]){
  List<String> myList = new ArrayList<> ();
  
  /* Add Elements to myList */
  myList.add("Hi");
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.add("How");
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.add("Are");
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  myList.add("You");
  System.out.println("Elements in myList are");
  System.out.println(myList);
 }
}

Output
Elements in myList are
[Hi]
Elements in myList are
[Hi, How]
Elements in myList are
[Hi, How, Are]
Elements in myList are
[Hi, How, Are, You]

1. throws UnsupportedOperationException if the add operation is not supported by this list

import java.util.*;
class ListAddUnsupport{
 public static void main(String args[]){
  List<String> myList = new ArrayList<> ();
  List<String> unModifyList;
  
  /* Add Elements to myList */
  myList.add("Hi");
  myList.add("How");
  myList.add("Are");
  myList.add("You");
  
  unModifyList = Collections.unmodifiableList(myList);
  System.out.println("Elements in unModifyList are");
  System.out.println(unModifyList);
  
  /* Trying to add Element to unmodifiable list */
  unModifyList.add("abcd");
 }
}
Since “ unModifyList” is a unmodifiable list, so adding element to the unmodifiable list cause “UnsupportedOperationException”.

Elements in unModifyList are
[Hi, How, Are, You]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
        at ListAddUnsupport.main(ListAddUnsupport.java:18)


2. throws ClassCastException if the class of the specified element prevents it from being added to this list

3. throws NullPointerException if the specified element is null and this
list does not permit null elements

4. throws IllegalArgumentException if some property of this element
prevents it from being added to this list



Prevoius                                                 Next                                                 Home

Copy List Data to Array of Specific Type

<T> T[] toArray(T[] a)
    Returns an array containing all of the elements in this list in proper sequence the run time type of the returned array is that of the specified array.


import java.util.*;
class ListSpecificArray{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  Integer myArray[];
  Integer retArray[];
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(123);
  myList.add(321);
  myList.add(456);
  
  int size = myList.size();
  
  myArray = new Integer[size];
  retArray = new Integer[size];
  
  retArray = myList.toArray(myArray);
  
  System.out.println("Elements in the list are");
  System.out.println(myList);
  
  System.out.println("Elements in myArray are");
  for(int i: myArray)
   System.out.print(i +" ");
   
  System.out.println("\n Elements in the retArray are");
  for(int i: retArray)
   System.out.print(i +" ");
   
 }
}

Output
Elements in the list are
[10, 123, 321, 456]
Elements in myArray are
10 123 321 456
 Elements in the retArray are
10 123 321 456

1. If the Array size is more than the number of elements in the list, then the element in the array immediately following the end of the list is set to null.
import java.util.*;
class ListSpecificArray{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  Integer myArray[];
  Integer retArray[];
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(123);
  myList.add(321);
  myList.add(456);
  
  int size = myList.size();
  
  myArray = new Integer[2*size];
  retArray = new Integer[2*size];
  
  retArray = myList.toArray(myArray);
  
  System.out.println("Elements in the list are");
  System.out.println(myList);
  
  System.out.println("Elements in myArray are");
  for(Integer i: myArray)
   System.out.print(i +" ");
   
  System.out.println("\n Elements in the retArray are");
  for(Integer i: retArray)
   System.out.print(i +" ");
   
 }
}

Output
Elements in the list are
[10, 123, 321, 456]
Elements in myArray are
10 123 321 456 null null null null
 Elements in the retArray are
10 123 321 456 null null null null


2. toArray() throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list

import java.util.*;
class ListSpecificArrayStore{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  Float myArray[];
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(123);
  myList.add(321);
  myList.add(456);
  
  int size = myList.size();
  
  myArray = new Float[size];
  
  myList.toArray(myArray);
  
  System.out.println("Elements in myArray are");
  for(float i: myArray)
   System.out.print(i +" ");
 }
}

When you tries to run the above program, run time throws “ArrayStoreException”. Since the list is of type Integer, where as the destination is of type Float. Both are incompatible.

Exception in thread "main" java.lang.ArrayStoreException
        at java.lang.System.arraycopy(Native Method)
        at java.util.ArrayList.toArray(Unknown Source)
        at ListSpecificArrayStore.main(ListSpecificArrayStore.java:18)

3.toArray() throws NullPointerException if the specified array is nul
import java.util.*;
class ListSpecificArrayNull{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  Integer myArray[];
  myArray = null;
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(123);
  myList.add(321);
  myList.add(456);
  
  int size = myList.size();
  
  myList.toArray(myArray);
  
  System.out.println("Elements in myArray are");
  for(Integer i: myArray)
   System.out.print(i +" ");
 }
}

Since “myArray” is initialized to null, so at run time NullPointerException thrown.


Exception in thread "main" java.lang.NullPointerException
        at java.util.ArrayList.toArray(Unknown Source)
        at ListSpecificArrayNull.main(ListSpecificArrayNull.java:17)






Prevoius                                                 Next                                                 Home

Monday, 31 March 2014

HierarchyListener



The listener interface for receiving hierarchy changed events. When the hierarchy to which the Component belongs changes, the hierarchyChanged method in the listener object is invoked, and the HierarchyEvent is passed to it. 

import java.awt.*;
import java.awt.event.*;

class HierarchyListenerInterfEx implements HierarchyListener{
 public void hierarchyChanged(HierarchyEvent e){
  System.out.println("Hierarchy Changed");
 }
}


import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

class HierarchyListenerEx{
 public static void main(String args[])throws Exception{
  JFrame myFrame = new JFrame("Event Handling Example");
  JButton button1 = new JButton("Button 1");
  HierarchyListenerInterfEx obj1 = new HierarchyListenerInterfEx();
  int count = 0;

  myFrame.setSize(250, 250);
  
  /* Add Buttons to Button */
  myFrame.add(button1);
  
  /* Register Focus Lister */
  myFrame.getContentPane().addHierarchyListener(obj1);
  for(int i=0; i < 5; i++){
   System.out.println("About to set visible status true");
   myFrame.setVisible(true);
   Thread.sleep(3000);
   System.out.println("About to set visible status false");
   myFrame.setVisible(false);
  } 
 }
}

Output


Prevoius                                                 Next                                                 Home

HierarchyBoundsListener



The listener interface for receiving ancestor moved and resized events. When the hierarchy to which the Component belongs changes by the resizing or movement of an ancestor, the relevant method in the listener object is invoked, and the HierarchyEvent is passed to it.

void ancestorMoved(HierarchyEvent e)
    Called when an ancestor of the source is moved.

void ancestorResized(HierarchyEvent e)
    Called when an ancestor of the source is resized.

import java.awt.*;
import java.awt.event.*;

class HierarchyBoundsListenerInterfEx implements HierarchyBoundsListener{

 public void ancestorMoved(HierarchyEvent e){
  System.out.println("Hierarchy Added");
 }
 
 public void ancestorResized(HierarchyEvent e){
  System.out.println("Hierarchy Removed");
 }
}


import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

class HierarchyBoundsListenerEx{
 public static void main(String args[])throws Exception{
  JFrame myFrame = new JFrame("Event Handling Example");
  JButton button1 = new JButton("Button 1");
  HierarchyBoundsListenerInterfEx obj1 = new HierarchyBoundsListenerInterfEx();
  int count = 0;
  
  myFrame.setVisible(true);
  myFrame.setSize(250, 250);
  
  String str;
  
  /* Register Focus Lister */
  myFrame.getContentPane().addHierarchyBoundsListener(obj1);
  
  /* Add Buttons to Button */
  myFrame.add(button1);
  
 }
}

Output

Try to resize the window using Mouse, You will get the Output Screen like below.



Prevoius                                                 Next                                                 Home

FocusListener



public interface FocusListener extends EventListener {
    public void focusGained(FocusEvent e);
    public void focusLost(FocusEvent e);
}

The listener interface for receiving keyboard focus events on a component. When the component gains or loses the keyboard focus, the relevant method in the listener object is invoked, and the FocusEvent is passed to it.


import java.awt.*;
import java.awt.event.*;

class FocusListenerInterfEx implements FocusListener{

 public void focusGained(FocusEvent e){
  System.out.println("Focus Added");
 }
 
 public void focusLost(FocusEvent e){
  System.out.println("Focus Removed");
 }
}


import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

class FocusListenerEx{
 public static void main(String args[])throws Exception{
  JFrame myFrame = new JFrame("Event Handling Example");
  JButton button1 = new JButton("Button 1");
  FocusListenerInterfEx obj1 = new FocusListenerInterfEx();
  int count = 0;
  
  myFrame.setVisible(true);
  myFrame.setSize(250, 250);
  
  String str;
  
  /* Register Focus Lister */
  button1.addFocusListener(obj1);
  
  /* Add Buttons to Button */
  myFrame.add(button1);
  
 }
}

Output






Prevoius                                                 Next                                                 Home

ContainerListener



public interface ContainerListener extends EventListener {
    public void componentAdded(ContainerEvent e);
    public void componentRemoved(ContainerEvent e);
}

The listener interface for receiving container events. Whenever some components added or removed from the container, the events called.
  
void componentAdded(ContainerEvent e)
    Invoked when a component has been added to the container.

void componentRemoved(ContainerEvent e)
    Invoked when a component has been removed from the container.

import java.awt.*;
import java.awt.event.*;

class ContainerListenerInterfEx implements ContainerListener{

 public void componentAdded(ContainerEvent e){
  System.out.println("Component Added");
 }
 
 public void componentRemoved(ContainerEvent e){
  System.out.println("Component Removed");
 }
}


import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

class ContainerListenerEx{
 public static void main(String args[])throws Exception{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  JFrame myFrame = new JFrame("Event Handling Example");
  JPanel buttonPanel;
  ContainerListenerInterfEx obj1 = new ContainerListenerInterfEx();
  int count = 0;
  
  myFrame.setVisible(true);
  myFrame.setSize(250, 250);
  
  String str;
  
  buttonPanel = new JPanel(new GridLayout(1,1));
  buttonPanel.setPreferredSize(new Dimension(200, 75));
  buttonPanel.addContainerListener(obj1);
  myFrame.add(buttonPanel);
  
  /* Create 100 Buttons */
  JButton myButton[] = new JButton[100];
  
  for(int i=0; i < 100; i++){
   myButton[i] = new JButton("Button " +i);
  }
    
  do{
   System.out.println("Enter Y to add one more button OR N to remove Button");
   str = br.readLine();
   /* Add Button to the frame */
   if(str.equals("Y")){
    buttonPanel.add(myButton[count]);
    count++;
   }
   
   /* Remove Button From the Frame */
   if(str.equals("N") && count != 0){ 
     buttonPanel.remove(myButton[--count]);
   }
   
   buttonPanel.revalidate();
   buttonPanel.repaint();
  }while(str.equals("Y") || str.equals("N"));
  System.exit(0);
 }
}

Output Screens






Prevoius                                                 Next                                                 Home