简体   繁体   English

为什么我的方法覆盖会产生类型冲突?

[英]Why does my method override give a type clash?

I need help to understand how the testing should go through.我需要帮助来了解如何通过 go 进行测试。 I should implement the test method in Stacktest.java (have already done that).我应该在Stacktest.java中实现测试方法(已经这样做了)。 Then extend StackTest with LinkedlistTest (I have already done that).然后用LinkedlistTest StackTest我已经这样做了)。 Then add super.setUp() as the first line in LinkedListTest.setUp (I have done that).然后添加 super.setUp() 作为LinkedListTest.setUp的第一行(我已经这样做了)。

But the one overriden method is getIntegerStack that I implement in the LinkedListTest , but then I get an error:但是一个被覆盖的方法是我在LinkedListTest中实现的getIntegerStack ,但随后出现错误:

'getIntegerStack()' in 'LinkedListTest' clashes with 'getIntegerStack()' in 'StackTest'; attempting to use incompatible return type

I dont know how to fix it.我不知道如何解决它。 The code:编码:

  • StackTest.java is an abstract test class. StackTest.java是一个抽象测试 class。
  • For each implementation of Stack , one may simply extend StackTest with an implementing test class.对于Stack的每个实现,可以简单地使用实现测试 class 扩展StackTest The only method that should be overridden is StackTest.getIntegerStack , which should simply return an instance of a class that implements Stack<Integer> .唯一应该被覆盖的方法是StackTest.getIntegerStack ,它应该简单地返回实现Stack<Integer>的 class 的实例。 See the setUp method in StackTest and try to understand how this works.查看StackTest中的setUp方法并尝试了解它是如何工作的。
  • In your case, you should extend StackTest with a test class called LinkedListTest .在您的情况下,您应该使用名为LinkedListTest的测试 class 扩展StackTest
  • you must add a call to super.setUp() ;您必须添加对super.setUp()的调用; as the first line in LinkedList.setUp() .作为LinkedList.setUp()的第一行。

TODO: How should I make the getIntegerStack() do work. TODO:我应该如何让getIntegerStack()工作。

import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Stack;

/**
 * Test class for LinkedList
 */
public class LinkedListTest extends StackTest{

    /* A sequence of integers */
    private int[] elements;

    /* An empty linked list */
    private LinkedList<Integer> list;

    @Before
    public void setUp() {
        super.setUp();
        list = new LinkedList<Integer>();
        elements = new int[]{-919,  388,   67, -248, -309, -725,  904,   53,
                90, -469, -559,  256,  612,  366, -412, -221,
                347, -921, -978,  324, -858,  480, -443,  891,
                329,   -5,  878, -538,  445, -366,  760,   52};
    }

    /**
     * This is the only method that implementing classes need to override.
     *
     * @return An instance of Stack.
     */
    @Override
    protected Stack<Integer> getIntegerStack() {
        return null;
    }
}

Stack interface:堆栈接口:

  * A interface of stack
  */
 public interface Stack <T> {
     /**
      * Adds the element to the top of the stack.
      */
     void push (T elem);
    
      T pop();

      T top();

     int size();

     boolean isEmpty();
 }
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
/**
 * A singly linked list.
 *
 */
public class LinkedList<T> implements Stack <T> {
    private ListElement<T> first;   // First element in list.
    private ListElement<T> last;    // Last element in list.
    private int size;  // Number of elements in list.

    /**
     * A list element.
     */
    private static class ListElement<T>{
        public T data;
        public ListElement<T> next;

        public ListElement(T data) {
            this.data = data;
            this.next = null;
        }
    }

    /**
     * Creates an empty list.
     */
    public LinkedList() {
        this.first = null;
        this.last = null;
        this.size = 0;
    }

    /**
     * Inserts the given element at the beginning of this list.
     *
     * @param element An element to insert into the list.
     */
    public void addFirst(T element) {
        ListElement<T> firstElement = new ListElement<>(element);
        if (this.size == 0){
            this.first = firstElement;
            this.last = firstElement;
        }
        else{
            firstElement.next = this.first;
            this.first = firstElement;
        }
        this.size ++;
    }

    /**
     * Inserts the given element at the end of this list.
     *
     * @param element An element to insert into the list.
     */
    public void addLast(T element) {
        ListElement<T> lastElement = new ListElement<>(element);
        if(this.size ==0){
            this.first = lastElement;
        }
        else{
            this.last.next = lastElement;
        }
        this.last = lastElement;
        this.size ++;
    }

    /**
     * @return The head of the list.
     * @throws NoSuchElementException if the list is empty.
     */
    public T getFirst() {
        if (this.first != null){
            return this.first.data;
        }
        else{
            throw new NoSuchElementException();
        }
    }

    /**
     * @return The tail of the list.
     * @throws NoSuchElementException if the list is empty.
     */
    public T getLast() {
        if(this.last != null){
            return this.last.data;
        }
        else{
            throw new NoSuchElementException();
        }
    }

    /**
     * Returns an element from a specified index.
     *
     * @param index A list index.
     * @return The element at the specified index.
     * @throws IndexOutOfBoundsException if the index is out of bounds.
     */
    public T get(int index) {
        if(index < 0|| index >= this.size){
            throw new IndexOutOfBoundsException();
        }
        else{
            ListElement<T>element = this.first;
            for(int i = 0; i < index; i++){
                element = element.next;
            }
            return element.data;
        }
    }

    /**
     * Removes the first element from the list.
     *
     * @return The removed element.
     * @throws NoSuchElementException if the list is empty.
     */
    public T removeFirst() {
        if(this.first != null || this.size != 0){
            ListElement<T> list = this.first;
            this.first = first.next;
            size --;
            if(size() == 0){
                last = null;
            }
            return list.data;
        }
        else{
            throw new NoSuchElementException();
        }
    }

    /**
     * Removes all of the elements from the list.
     */
    public void clear() {
        this.first = null;
        this.last = null;
        this.size =0;
    }

    /**
     * Adds the element to the top of the stock.
     * @param elem
     */
    @Override
    public void push(T elem) {
        ListElement <T> list = new ListElement<>(elem);
        if( first == null){
            first = list;
            last = first;
        } else{
            list.next = first;
            first = list;
        }
        size ++;
    }

    /**
     * Removes and returns the top element in stack,
     * that is the element that was last added.
     * Throws an EmptyStackException if stack is empty.
     * @return the top element in the stack.
     */
    @Override
    public T pop(){
        if(isEmpty()){
            throw new EmptyStackException();
        }else{
            ListElement <T> list = first;
            first = first.next;
            size --;

            return list.data;
        }
    }

    /**
     * returns the top element in the stack without removing it.
     * Throws an EmptyStackException if stack is empty.
     * @return the top element.
     */
    @Override
    public T top() {
        if(isEmpty()){
            throw new EmptyStackException();
        }else{
            return first.data;
        }
    }

    /**
     * Returns the number of elements in the stock
     * @return The number of elements in the stock.
     */
    public int size() {

        return this.size;
    }

    /**
     * Note that by definition, the list is empty if both first and last
     * are null, regardless of what value the size field holds (it should
     * be 0, otherwise something is wrong).
     *
     * @return <code>true</code> if this list contains no elements.
     */
    public boolean isEmpty() {

        return first == null && last == null;
    }

    /**
     * Creates a string representation of this list. The string
     * representation consists of a list of the elements enclosed in
     * square brackets ("[]"). Adjacent elements are separated by the
     * characters ", " (comma and space). Elements are converted to
     * strings by the method toString() inherited from Object.
     *
     * Examples:
     *  "[1, 4, 2, 3, 44]"
     *  "[]"
     *
     * @return A string representing the list.
     */
    public String toString() {
        ListElement<T> listOfElements = this.first;
        String returnString = "[";
        while(listOfElements != null) {
            returnString += listOfElements.data;
            if(listOfElements.next != null){
                returnString += ", ";
            }
            listOfElements = listOfElements.next;
        }
        returnString += "]";
        return returnString;
    }
}

import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.lang.Integer;
import java.util.EmptyStackException;
import java.util.stream.IntStream;

/**
 * Abstract test class for Stack implementations.
 *
 * Implementing test classes must only implement the getIntegerStack
 * method. Be careful not to override ANY other methods!
 *
 */
public abstract class StackTest{
    @Rule public Timeout globalTimeout = Timeout.seconds(5);

    private Stack<Integer> stack;
    private int[] valuesInStack;
    private int initialStackSize;
    private Stack<Integer> emptyStack;

    @Before
    public void setUp() {
        valuesInStack = new int[] {3, 4, 1, -123, 4, 1};
        initialStackSize = valuesInStack.length;
        stack = getIntegerStack();
        pushArrayToStack(valuesInStack, stack);
        emptyStack = getIntegerStack();
    }

    /**
     * Push an array to the stack, in order.
     *
     * @param array An int array.
     * @param stack A Stack.
     */
    private void pushArrayToStack(int[] array, Stack<Integer> stack) {
        for (int i = 0; i < array.length; i++) {
            stack.push(array[i]);
        }
    }

    /**
     * This is the only method that implementing classes need to override.
     *
     * @return An instance of Stack.
     */
    protected abstract Stack<Integer> getIntegerStack();

    @Test
    public void topIsLastPushedValue() {
        // Arrange
        int value = 1338;

        // Act
        emptyStack.push(value);
        stack.push(value);

        int emptyStackTop = emptyStack.top();
        int stackTop = stack.top();

        // Assert
       assertThat(emptyStackTop, equalTo(value));
     assertThat(stackTop, equalTo(value));
    }

    // HELPERS

    /**
     * Pops the desired amount of elements.
     *
     * @param stack A Stack.
     * @param amountOfElements The amount of elements to pop.
     */
    private void popElements(Stack<Integer> stack, int amountOfElements) {
        for (int i = 0; i < amountOfElements; i++) {
            stack.pop();
        }
    }

    /**
     * Class used for stream operations when both actual and expected values
     * need to be gather in conjunction.
     */
    private class ResultPair<T> {
        public final T actual;
        public final T expected;

        public ResultPair(T actual, T expected) {
            this.actual = actual;
            this.expected = expected;
        }
    }
}

Your LinkedListTest class contains the erroneous line:您的LinkedListTest class 包含错误的行:

import java.util.Stack;

Because of that, the getIntegerStack() method returns a java.util.Stack object instead of an object of the Stack interface you created yourself.因此, getIntegerStack()方法返回java.util.Stack object 而不是您自己创建的Stack接口的 object。

Just dropping that import statement will fix your problem.只需删除该导入语句即可解决您的问题。

Unrelated to your problem, you can also let getIntegerStack() return any subclass of your Stack interface.与您的问题无关,您也可以让getIntegerStack()返回Stack接口的任何子类。 In this case it would be more natural to let it return your LinkedList :在这种情况下,让它返回您的LinkedList会更自然:

/**
 * In the context of `LinkedListTest` we return a `LinkedList`.
 *
 * @return An instance of Stack.
 */
@Override
protected LinkedList<Integer> getIntegerStack() {
    return new LinkedList<Integer>();
}

暂无
暂无

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

相关问题 名称冲突:类型为test2的方法add(Object)具有与HashSet类型的add(E)相同的擦除 <E> 但不会覆盖它 - Name clash: The method add(Object) of type test2 has the same erasure as add(E) of type HashSet<E> but does not override it 由于名称冲突,无法覆盖方法 - Cannot override a method because of a name clash 为什么在方法内部重写此方法会失败? - Why does this method override inside a method fail? 为什么示例中的函数之前的“@override”会出错? - Why does the “@override” before functions in examples give errors? 返回扩展类的类型给平台声明冲突 - Return the type of a extended class give platform declaration clash 为什么我的原始类型争论方法不会覆盖包装类型争论的超类方法? - Why doesn't my primitive-type-argumented method override the wrapper-type-argumented super class method? 为什么`System.out.println(null);`give“方法println(char [])对于类型PrintStream错误是不明确的”? - Why does `System.out.println(null);` give “The method println(char[]) is ambiguous for the type PrintStream error”? 我的班级没有覆盖抽象方法compareTo - My class does not override abstract method compareTo 为什么我的方法说它必须返回一个类型字符串并给我一个错误,即使我的方法确实返回一个类型字符串 - Why does my method say it must return a type string and gives me an error even though my method does return a type string 为什么我的方法没有为这种类型定义? - Why is my method undefined for this type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM