【问题标题】:Java Generics QuestionJava泛型问题
【发布时间】:2011-11-04 09:56:35
【问题描述】:

Queue12 是一个接口,QueueImp12 是Queue12 的一个实现。所以我正在尝试测试我的 QueueImp12 但是当我在 Eclipse 中运行它(它编译)时,我的输出在控制台中终止。我相信我正确地创建了 ringBuffer。如果我的测试看起来不错,那么我的实现或 Eclipse 一定有问题。谢谢

import java.util.NoSuchElementException;


public class QueueImpl12<T> implements Queue12<T> 
{

private int _size, _backIdx, _frontIdx;
private static final int _defaultCapacity = 128;
private T[] _ringBuffer;



public QueueImpl12(int capacity)
{
    _ringBuffer = (T[]) new Object[capacity];
    clear();    
}


public QueueImpl12()
{
    _ringBuffer = (T[]) new Object[_defaultCapacity];
    clear();
}

private int wrapIdx(int index)
{

    return index % capacity();
}



public void clear() 
{
    _backIdx = 0;
    _frontIdx = 0;
    _size = 0;

}

@Override
public int capacity() 
{
    // TODO Auto-generated method stub
    return _ringBuffer.length;
}

@Override
public int size() 
{
    // TODO Auto-generated method stub
    return _size;
}

@Override
public boolean enqueue(T o) 
{
    //add o to back of queue


    if(_ringBuffer.length == _size)
    {
        return false;
    }


       _ringBuffer[_backIdx] = o;
        _backIdx = wrapIdx(_backIdx + 1 );
        _size++;





    return true;
}

@Override
public T dequeue()
{
    if(_size == 0)  //empty list
    {
        throw new NoSuchElementException();
    }

    T tempObj = _ringBuffer[_frontIdx];     //store frontIdx object
    _ringBuffer[_frontIdx] = null;          
    _frontIdx++;



    _size--;
    return tempObj;
}

@Override
public T peek() 
{

    return _ringBuffer[_frontIdx];
}

}




public class P3test  
{
public static<T> void main(String[] args) 
{
    final Queue12<T> ringBuffer = new QueueImpl12<T>();
    T o = (T) new String("this");
    ringBuffer.enqueue(o); //add element to the back
    ringBuffer.dequeue();  //remove/return element in the front

}
 }

【问题讨论】:

  • 这不是有效的 Java 代码。请你解决它!
  • 重新格式化您的代码。我很明显它现在不会编译。 main 方法也不是测试,改天试试 JUint(TDD 太棒了)。
  • 为什么要将String 转换为T?这没有任何意义。 T 来自哪里?
  • 如果它编译,泛型部分应该没问题。您看到的具体问题是什么?它应该输出什么吗?
  • 我还有 2 个其他类,公共接口 Queue12{..} 和公共类 QueueImpl12 实现 Queue12{..} 我想通过 main 以某种方式对其进行测试,但没有不确定我可以在 enqueue() 中放入什么来测试它(现在开始学习 Junit/TDD)。我不明白什么类型 它只是对象类型?由于您不能将字符串直接放入队列中,因此我认为制作 T 类型的字符串会起作用。

标签: java eclipse generics queue circular-buffer


【解决方案1】:

您最近看到的“终止”是程序完成时的预期行为。

添加一些 System.outsasserts 以验证您的代码是否运行(在这里它运行,带有一些可怕的强制转换警告,但运行)

final Queue12<T> ringBuffer = new QueueImpl12<T>();
T o = (T) new String("this");
ringBuffer.enqueue(o); //add element to the back
System.out.println(ringBuffer.peek());//this should print 'this' in the console\
//assertEquals('this', ringBuffer.peek());
ringBuffer.dequeue();  //remove/return element in the front

了解如何使用泛型和测试。并且不要将泛型参数放在主函数中,在那里是没用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多