So far you have learnt about the Java built-in Collection Interfaces implementations.
So far you have learnt about the Java built-in Collection Interfaces implementations.So far you have learnt about the Java built-in Collection Interfaces implementations. Apart from these, some times programmer need to implement their own collections classes. The Java platform allows you to write your own implementation of a core collection interface. It is easy to write your own implementation with the help of abstract implementations.
Lets discuss, why we should make a custom implementation.
To write your own custom implementation is not difficult. Java supports the abstract implementations to implement your own collection. Lets see the way of writing the custom collection implementation.
import java.util.*; class MyClass { public static List myList(Object[] a) { return new ArrayList(a); } } class ArrayList extends AbstractList implements java.io.Serializable { private Object[] x; ArrayList(Object[] array) { x = array; } public Object get(int index) { return x[index]; } public Object set(int index, Object element) { Object oldVal = x[index]; x[index] = element; return oldVal; } public int size() { return x.length; } } public class CustomImpl{ public static void main(String[] args) { try{ String s[]={"My", "Custom", "Implementation"}; Object o; int i=0; MyClass a= new MyClass(); List lst=a.myList(s); System.out.println("The list is: "+lst); ArrayList al=new ArrayList(s); o=al.get(1); System.out.println("The retrieved element is: "+o); String s1="Collection"; o=al.set(2,s1); System.out.println("The set element in place of Implementation is: "+s1); System.out.println("Now the new list is: "+lst); i=al.size(); System.out.println("The size of the array list is: "+i); } catch(Exception e){} } }
Output of the Program:
C:\nisha>javac CustomImpl.java C:\nisha>java CustomImpl The list is: [My, Custom, Implementation] The retrieved element is: Custom The set element in place of Implementation is: Collection Now the new list is: [My, Custom, Collection] The size of the array list is: 3 C:\nisha> |
Description of the Program:
In the given program, a custom implementation of Arrays.myList is defined which calls the constructor of ArrayList class and pass the object to it. The get( ) and the set( ) methods of the ArrayList class retrieve and set an element to the specified position of the List.
Ads