I've only known a very small amount of Java in the past, and now I'm even having to refresh my memory on the most extreme basics. My background is mainly in C++.
Let's say you have an int array and want to initialize that array upon declaration to some starting values or whatever.
The basic way to do that is easy to locate on the Internet. However let's say you're trying to do that with a class that only employs a constructor that takes multiple arguments.Code:int arry[] = {1, 2, 3};
Yes, I know that technically the array can be filled in sometime after declaration, but what if I don't want to do that? What if I want to initialize the array instantly like with the int array above? How do I handle the fact that the class's only constructor (if there is a default constructor put there anyway, I don't want to use it) has multiple parameters? That is something that is not so easy to find on the Internet. Thanks!Code:public class position extends object { /* an almost pointless class */ public position(int x, int y) { xPos = x; yPos = y; } public int xPos; public int yPos; }
Code:position map[] = ????
so do you mean something like:
OR (probably better)Code:public class Test { int[] intArray; public Test(int a, int b, int c) { int[] tempIntArray = {a,b,c}; intArray = tempIntArray; } }
?Code:public class Test { int[] intArray; public Test(int a, int b, int c) { intArray = new int[] {a,b,c}; } }
According to java convention, all Class names are starting with Capital Letters.
I'm exactly not sure what you meant. If you don't want to fill it instantly, then write:Code:public class Test{ Position pos[] = { new Position(1, 2), new Position(3, 4), new Position(5, 6) }; } class Position{ /* an almost pointless class */ public Position(int x, int y) { xPos = x; yPos = y; } public int xPos; public int yPos; }
Code:Position pos[] = new Position[yourArrayLength]();
Yes, that worked out quite well. Thank you. The example you showed that had the three consecutive new Position declarations in class Test was basically what I asking for. It's quite easy to find the information on how to initialize an array upon declaration when you're just dealing with stuff like integers for instance, but obviously you can't just say (in those examples)
nor can you sayCode:Position arry[] = { new Position, new Position };
So I was just wondering about the syntax, which you answered. Thanks!Code:Position arry[] = {{2, 3}, {5,6}};
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks