To implement a custom Collection in Java, you need to create a class that implements the Collection interface or extends an existing Collection class. The Collection interface defines the basic operations that any Collection should support, such as adding and removing elements, checking if an element is contained in the collection, and iterating over the collection. Here’s an example of a custom Collection class that implements the Collection interface:
import java.util.*;
public class MyCollection<E> implements Collection<E> {
private List<E> list;
public MyCollection() {
list = new ArrayList<E>();
}
// Implement the Collection interface methods
public boolean add(E element) {
return list.add(element);
}
public boolean addAll(Collection<? extends E> collection) {
return list.addAll(collection);
}
public void clear() {
list.clear();
}
public boolean contains(Object element) {
return list.contains(element);
}
public boolean containsAll(Collection<?> collection) {
return list.containsAll(collection);
}
public boolean isEmpty() {
return list.isEmpty();
}
public Iterator<E> iterator() {
return list.iterator();
}
public boolean remove(Object element) {
return list.remove(element);
}
public boolean removeAll(Collection<?> collection) {
return list.removeAll(collection);
}
public boolean retainAll(Collection<?> collection) {
return list.retainAll(collection);
}
public int size() {
return list.size();
}
public Object[] toArray() {
return list.toArray();
}
public <T> T[] toArray(T[] array) {
return list.toArray(array);
}
}
In this example, we define a MyCollection class that uses an ArrayList to store its elements. The MyCollection class implements all the methods of the Collection interface, which allows us to add, remove, and iterate over the elements in the collection.
To use the MyCollection class, we can create an instance of it and then add elements to it using the add() method:
MyCollection<String> myCollection = new MyCollection<String>();
myCollection.add("apple");
myCollection.add("banana");
myCollection.add("cherry");
Once we have added elements to the collection, we can use any of the other methods of the Collection interface to manipulate or access the elements. Note that the implementation of the methods in MyCollection can be customized to provide specific behavior or optimizations depending on the needs of the application.