我确信这对很多人来说都是一个非常简单的问题,但我正在努力解决这个问题。我试图从以下构造函数中获取一个值并将其放入 vector 中。
每次我将对象添加到 vector 中时,放置在 vector 内的值为空。如何将数字作为放入 vector 中的值?
CInteger 类:
public class CInteger
{
private int i;
CInteger(int ii)
{
i = ii;
}
}
在我的 A1 类中,构造函数和我获取值的尝试:
Object enqueue(Object o)
{
CInteger ci = new CInteger(88);
Object d = ??
add(tailIndex, d);// add the item at the tail
}
感谢大家的见解和帮助,我仍在学习中。
编辑:已解决
CInteger 类:
public class CInteger implements Cloneable // Cloneable Integer
{
int i;
CInteger(int ii)
{
this.i = ii;
}
public int getValue()
{
return i;
}
}
两种入队方法:
public void enqueue(CInteger i) // enqueue() for the CInteger
{
add(tailIndex, new Integer(i.getValue())); get int value and cast to Int object
}
public void enqueue(Date d) // enqueue() for the Date object
{
add(tailIndex, d);
}
非常感谢大家。 :D
最佳答案
您可以简单地重载队列类以获取日期和整数。无论哪种情况,听起来您都需要 CInteger 中的 getValue() 方法来访问 int 值。
public class CInteger
{
//constructors, data
public void getValue()
{
return i;
}
}
然后你可以在另一个类中有两个 enqueue() 方法:
public void enqueue(Date d)
{
add(tailIndex, d);
}
public void enqueue(CInteger i)
{
add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object
}
Java会根据参数自动知道你调用的是哪一个。
关于java - 从另一个类的构造函数中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5373389/