someGenericCollectionInstance

someGenericCollectionInstance

如何创建一个通用的Java集合,该集合将打印出如下所示的值:
(带小括号,不带逗号)

SomeGenericCollection someGenericCollectionInstance = new SomeGenericColllection();

someGenericCollectionInstance.add("A");
someGenericCollectionInstance.add("B");

System.out.println(someGenericCollectionInstance);


预期输出为:

(“ A”“ B”)

其他情况:

SomeGenericCollection someGenericCollectionInstance = new SomeGenericColllection();

someGenericCollectionInstance.add(1);
someGenericCollectionInstance.add(2);

System.out.println(someGenericCollectionInstance);


(1 2)

最佳答案

如果我理解正确,则只想覆盖AbstractCollectiontoString方法。
像这样 :

public abstract class MyCollection<E> extends AbstractCollection<E> {

@Override
public String toString() {
    Iterator<E> it = iterator();
    if (! it.hasNext())
        return "()";

    StringBuilder sb = new StringBuilder();
    sb.append('(');
    for (;;) {
        E e = it.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
            return sb.append(')').toString();
        sb.append(' ');
    }
}


}

08-17 23:11