从另一个类的构造函数中获取价值
我相信这对于很多人来说是一个非常简单的问题,但我正在为此付出努力。我试图从下面的构造函数中获取一个值并将其放入一个向量中。从另一个类的构造函数中获取价值
虽然每次将对象添加到矢量中,但放置在矢量中的值都为null。我怎样才能让数字成为向量中放置的值?
的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
您可以简单地重载enqueue类以同时采用日期和整数。无论哪种情况,听起来您都需要在CInteger中使用getValue()方法,该方法允许您访问int值。
public class CInteger
{
//constructors, data
public void getValue()
{
return i;
}
}
,然后你可以有两个排队()方法在其他类:
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会知道哪一个您所呼叫自动根据参数。
非常感谢你!这工作完美! – Jordan 2011-03-21 03:32:27
这是不完全清楚你实际上是试图做的,但我认为这就够了:
Object enqueue() {
CInteger ci = new CInteger(88);
add(tailIndex, ci);// add the item at the tail
return ci; // this will automatically upcast ci as an Object
}
感谢您的回复。不过,我已经尝试过这一点,并且在打印出矢量内容时仍然将值设为null。 – Jordan 2011-03-21 03:16:05
试试这个。
public class CInteger {
private int i;
CInteger(int ii) {
this.i = ii;
}
}
“这个”在这里不会有所作为,对吧? – 2011-03-21 03:49:13
岂不只是:
void main(string[] args)
{
CInteger ci = new CInteger(88);
encqueue(ci.i);
}
Object enqueue(Object o)
{
add(tailIndex, o);
}
还是我失去了一些东西?
是的,只有在CInteger构造函数处于enqueue方法时才有效。我需要main()中的构造函数。 – Jordan 2011-03-21 03:28:08
嗯,根据你的问题,你真的不清楚你想要完成什么。你是否想要构造一个CInteger,然后排入它的基础值或什么? – 2011-03-21 03:33:17
好吧,我更新了我的答案以反映这一点,但我仍然只有34.5%左右确定你实际上想要做的事情。 – 2011-03-21 03:48:50
首先,Constructors永远不会返回任何值。您必须通过其对象访问该值,或者必须使用getter方法。
对您而言,“private int i;
”无法直接访问。所以尽量让它成为公共的或者有一些getter方法。
所以尝试:
CInteger ci = new CInteger(88);
Object d = ci.i; // if i is public member
add(tailIndex, d);
或
...
private int i;
...
public int getI() {
return this.i;
}
...
CInteger ci = new CInteger(88);
Object d = ci.getI();
add(tailIndex, d);
究竟是你想设置 “d” 来? – 2011-03-21 03:02:20
我想从CInteger中设置“d”为int值“88”。除了对象之外,我不能拥有排队的参数,因为之后我会排入一个“Date”对象。 – Jordan 2011-03-21 03:18:56
为什么enqueue有一个参数?你是否试图入选Object o或CInteger ci? – donnyton 2011-03-21 03:19:10