简体   繁体   English

什么参数应该为泛型集添加函数accept <E> 在java?

[英]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. 我正在尝试用Java编写一个Set<E>接口,它将由另一个类mySet<E>实现,利用arrayList<E>来存储元素。

I intend to include regular set functions: add() , remove() , union() intersection() etc. 我打算包括常规的set函数: add()remove()union() intersection()等。

What should the type be for my add() and remove() functions? 我的add()remove()函数的类型应该是什么? I have tried using add(Object E) and add(<E>) but am running into errors. 我尝试过使用add(Object E)add(<E>)但遇到了错误。

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

Reference - Generics In Java 参考 - Java中的泛型

A Set<K> would usually extend AbstractSet<K> and implement: Set<K>通常会扩展AbstractSet<K>并实现:

@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. 希望这能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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