Introduction

In this article, we are going to describe the implementation of a custom collection in Java. I begin by describing what a custom collection implementation is; then after all, why we need it. So I give you an appropriate reason.

Custom Collection Implementation

custom collection in Java
Most of the time many programmers will never 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. However, someday you might want to write your own implementation. It is fairly easy to do this with the aid of the abstract implementations provided by the Java platform. Before we discuss how to write an implementation, let's discuss why you might want to write one. You can go pretty far using the implementations described in the preceding sections of this article.

Why we use custom Collection implementation

There are the following reasons for sort of custom collection you might want to implement. These are taken from Reference

Custom Collection in Java Example

To write your own custom implementation is not difficult. Java supports the abstract implementations to implement your own collection. Let's see how to write the custom collection implementation.
Code
  1. import java.util.*;
  2. class MyClass {
  3. public static List myList(Object[] a) {
  4. return new ArrayList(a);
  5. }
  6. }
  7. class ArrayList extends AbstractList implements java.io.Serializable {
  8. private Object[] x;
  9. ArrayList(Object[] array) {
  10. x = array;
  11. }
  12. public Object get(int index) {
  13. return x[index];
  14. }
  15. public Object set(int index, Object element) {
  16. Object oldVal = x[index];
  17. x[index] = element;
  18. return oldVal;
  19. }
  20. public int size() {
  21. return x.length;
  22. }
  23. }
  24. public class CustomCollectionDemo {
  25. public static void main(String[] args) {
  26. try {
  27. String s[] = {
  28. "This ",
  29. "is",
  30. "custom",
  31. "Collection",
  32. "Implementation"
  33. };
  34. Object o;
  35. int i = 0;
  36. MyClass a = new MyClass();
  37. List lst = a.myList(s);
  38. System.out.println("The list is: " + lst);
  39. ArrayList al = new ArrayList(s);
  40. o = al.get(1);
  41. System.out.println("The retrieved element is: " + o);
  42. String s1 = "Collection";
  43. o = al.set(2, s1);
  44. System.out
  45. .println("The set element in place of Implementation is: "
  46. +
  47. s1);
  48. System.out.println("Now the new list is: " + lst);
  49. i = al.size();
  50. System.out.println("The size of the array list is: " + i);
  51. } catch (Exception e) {
  52. }
  53. }
  54. }
OUTPUT
custom collection in Java