File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes reassigning arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "reassigning arrays" Watch "reassigning arrays" New topic
Author

reassigning arrays

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
I have a program that looks something like this, but longer, of course.

public class MixPict {
int r = 2;
int[] order = {0,1,2,3};
}
public class TesttheMixPict {
public static void main (String [] args) {
MixPict m = new MixPict();
m.r = 3;
m.order = {1,0,2,3,4,5,6,7,8};
}
}
The MixPict class compiled OK and the m.r=3 line compiled, but the m.order={1,0,2,3,4,5,6,7,8} did not compile. I got an error message of illegal start of expression. Why?
In my thinking, because you can do this:
Dog a = new Dog
Dog b = new Dog
a = b
you should be able to do my program. After all, the third line of the dog example assigns a new object to the variable a, and the m.order={1,0,2,3,4,5,6,7,8} line of my program assigns a new object to the variable m.order.
m.order is declared as an integer array, and {1,0,2,3,4,5,6,7,8} is an array of integers, isn't it? So why doesn't it work?
Could it be that the first assignment of m.order declares m.order as an int[4] array, and the second assignment tries to make it into an int[9] array, and int[4] and int[9] are different, as in this example:
Dog adog = new Dog
Cat acat = new Cat
adog = acat // can't compile because you can't assign a cat object to a dog variable
?
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9047
    
  10

Two shortcut ways to initialize an array are
int[] order = {0,1,2,3};
and
m.order = new int[]{1,0,2,3,4,5,6,7,8};

The first lets you declare, construct, and initialize an array as one statement. The second lets you construct and initialize a previously declared array. Unfortunately, the way you tried does not fit into either of these categories. You are trying to initialize a new array without the "new" keyword after you have already declared that array. Arrays are funny objects and this is one thing that does not work.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
jiju ka
Ranch Hand

Joined: Oct 12, 2004
Posts: 306

int[] order = {0,1,2,3};


The fact that java tolerates the above but not the statement below is really frustrating to beginners/and evrybody. Almost every developers might have come across this inconsistency atleast once.

Is there any reason Sun specified why the 'new' can't be infered for the code below?


order = {0,1,2,3};
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: reassigning arrays