0

so I have tried searching for the answer to this question, but really don't know exactly how to find my answer. I am trying to insert values into an array, whose elements i declared previously in the same class. It does not work as far as I can tell. The element will change, but not the original variable the element represents. Is this because they are not the same variable (the array makes a copy or something? I hope this makes sense, but if not here is some sample code:

public class bucky {
public static void main(String args[]) {

    tuna tunaObject = new tuna();
    tunaObject.assignArray(25);
}
}

.

public class tuna {
int day;
int month;
int year;

int dateArray[] = {day, month, year};

void assignArray(int dayInput){
    dateArray[0] = dayInput;
    System.out.println(dateArray[0]);
    System.out.println(day);
 }
}

The output is: 25 0

So clearly day does not get altered. Though I wish it would, and wonder how I can make this work.

Unfortunately it's late. I've been working at this for hours. I'm tired. And I'm pretty sure the clocks just rolled back an hour on me.... Knowing the answer to why this doesn't work would make it all worth while. Cheers!

4

4 回答 4

1

int是一个值类型,而不是引用类型,所以dayanddateArray不存储对值的引用,而是存储实际值。

如果您还想将新值分配给day,则必须明确执行此操作:

void assignArray(int dayInput){
    dateArray[0] = dayInput;
    day = dayInput;
}
于 2012-11-04T10:23:04.817 回答
0

您显然是 Java 新手(从您不使用 Java 约定我可以看出),并且您应该知道对于您的这种特殊情况,这种指针的东西不会在 Java 中发生。

原始类型(在您的情况下为整数)不是通过引用传递的,而是通过值传递的。

您的问题的解决方案是添加另一行

day = dateInput
dateArray[0] = day

每次更新一天的值。

于 2012-11-04T10:32:23.763 回答
0

创建 dateArray 时,您会通过复制日期、月份和年份的值来影响值。那些不是参考。所以不要期望通过修改数组值来改变你的属性。

于 2012-11-04T10:23:25.693 回答
0

day是 class 的实例变量Tuna,并且您的数组是 int 类型,它仅在其第一个索引处使用 date (一个 int 变量)。因此,您的 dateArray 只是在其第一个索引处使用 day 的值。

   int day=12;

    int dateArray[] = {day}; 

现在 dateArray 的第一个索引值为 12。

于 2012-11-04T10:19:40.623 回答