简体   繁体   中英

What arguments should add function accept for generic set<E> in java?

I am trying to write a Set<E> interface in Java, that will be implemented by another class mySet<E> utilising an arrayList<E> to store the elements.

I intend to include regular set functions: add() , remove() , union() intersection() etc.

What should the type be for my add() and remove() functions? I have tried using add(Object E) and add(<E>) but am running into errors.

add(E objToAdd);
remove(E objToRemove);

Reference - Generics In Java

A Set<K> would usually extend AbstractSet<K> and implement:

@Override
public Iterator<K> iterator() {

@Override
public boolean add(K k) {

@Override
public int size() {

@Override
public boolean contains(Object o) {

Whenever we write an implementation of generics type We use the same type notation as that of the interface/class.

public interface ISet<E>{
    boolean add(E element);
    boolean remove(E element);
}

As per your question as you need to create an implementation of this you can try the below sample code:

public class MySet<E> implements ISet<E>{
    private List<E> myInnerList = new ArrayList<E>();

    public boolean add(T element){
        //write you code here for adding the element
        // i.e. myInnerList.add(element);
        return false;
    }

    public boolean remove(T element){
        //write you code here for adding the element
        // i.e. myInnerList.remove(element);
        return false;
    }
}

Hope this solves your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM