gpt4 book ai didi

java - 查看我的 Java 泛型通配符

转载 作者:行者123 更新时间:2023-11-30 10:57:38 24 4
gpt4 key购买 nike

在下面的代码中,我不知道我是否正确编码了最后一个方法 public boolean addAll(SimpleSet<? extends E> s) {你能检查一下它是否正确吗(请向我解释 (SimpleSet<? extends E> s) 是如何工作的)并看看其他方法!

package set;
import java.util.ArrayList;
import java.util.Iterator;

public class ArraySet<E> implements SimpleSet<E> {
private ArrayList<E> data=new ArrayList<E>();

/**
* Constructs a new empty set.
*/
public ArraySet() {

}

/**
* Adds the specified element to this set, if it is not already present.
* post: x is added to the set if it is not already present
* @param x the element to be added
* @return true if the specified element was added
*/
public boolean add(E x) {
for(int i=0; i<data.size(); i++){
if(data.get(i).equals(x)){
System.out.println("x is already added");
} else {
data.add(x);
System.out.println("x is added to the set");

return true;
}
}
return false;
}

/**
* Removes the specified element from this set if it is present.
* post: x is removed if it was present
* @param x the element to remove - if present
* @return true if the set contained the specified element
*/
public boolean remove(Object x) {
for(int i=0; i<data.size(); i++){
if(data.get(i).equals(x)){
data.remove(x);
return false;
}
}
return true;
}

/**
* Returns true if this set contains the specified element.
* @param x the element whose presence is to be tested
* @return true if this set contains the specified element
*/
public boolean contains(Object x) {
for(int i=0; i<data.size(); i++){
if(data.get(i).equals(x)){
return true;
}
}
return false;
}


/**
* Returns true if this set contains no elements.
* @return true if this set contains no elements
*/
public boolean isEmpty() {
if(data.size()==0){
return true;
}
return false;
}

/**
* Returns the number of elements in this set.
* @return the number of elements in this set
*/
public int size() {
return data.size();
}

/**
* Returns an iterator over the elements in this set.
* @return an iterator over the elements in this set
*/
public Iterator<E> iterator() {
return this.iterator();

}

/**
* Adds all of the elements in the specified set, for which it is
* possible, to this set.
* post: all elements, for which it is possible, in the
* specified set are added to this set.
* @return true if this set changed as a result of the call
*/
public boolean addAll(SimpleSet<? extends E> s) {
for(E e : s){
data.add(e);
System.out.println("all elements, for which it is possible, in the specified set are added to this set. ");
return true;
}
return false;
}

}

最佳答案

“? extends SomeClass”的基础是“?”代表作为 SomeClass 或 SomeClass 的任何子类的实例的对象。

addAll 的唯一问题是它接受“SimpleSet ”,而 Collection.addAll 的定义需要“Collection ”。您通过要求 Collection 的特定子类(“SimpleSet”)而不是任何类型的 Collection 来打破接口(interface)契约。这可能是一个编译时错误。

关于java - 查看我的 Java 泛型通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com