Why does this double have [] directly after it? - java

I've come across this piece of code in a program I'm editing for an assignment:
double[] colour = new double [3];
colour[0] = 255; colour[1] = 0; colour[2] = 0;
I think it means that the value colour is a double which is made by combining three other values. Is there anything more that needs to be said about this? I mean, is that why the double has the [] brackets directly after it - to specify that it needs to take more than one value? I'm slightly confused by this...

The [] means that you have an array of doubles. Arrays let you have multiple things in a sort of list, so you can have three numbers: [255, 0, 0]
More info is available in the Java array documentation: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

The [] indicates you are creating an "array of double". This is primitive array which means the size is fixed. In your case an array of size 3 is being allocated.
An alternate method would be to use the List interface:
List<Double> colour = new ArrayList<Double>(3);
colour.add(255);
colour.add(0);
colour.add(0);
For this example you could also have a class:
public class Colour {
double r;
double g;
double b;
public Colour(double r, double g, double b) {
this.r = r;
this.g = g;
this.b = b;
}
....
}

A double[] is an array of double values.
In your particular case, colour is an array of size 3 (as specified on the right hand side of the assignment), and so you will access the three components using colour[0], colour[1] and colour[2] respectively.

In Java the [] after a type denote Array data structures.
In your case, you are creating an array of 3 double values.
Please refer to this Oracle tutorial for more information regarding the matter.

The line:
double[] colour = new double [3];
say: length colour[] = 3, datatype double,
and:
colour[0] = 255; colour[1] = 0; colour[2] = 0;
asign to colour the values [255, 0, 0]
PD: I can't comment sorry.

Keeping in mind that [] denotes array, which can be thought of as a collection of objects (in this case, numbers of the double data type), you can think of it in layman's terms like this:
The double[] colour part of the statement kind of says "I am going to have this collection called colour and it's going to be a type of double number, but I don't know what values or how many it's going to have." Emphasis on the word collection, since that's what an array is.
The new double [3] part says "I am creating 3 new doubles". Since you never said what the 3 doubles are, you begin to state them:
"The first one is 255, the second one is 0, and the third one is 0.", which in the code looks like this now:
colour[0] = 255; colour[1] = 0; colour[2] = 0
And I'm sure you might already know, but in computers, the numbers start counting up from 0 instead of 1.
[0] [1] [2]
First Element Second Element Third Element
Another example that helped me better understand arrays when I first started programming was thinking of a box of Oreos that has different flavors inside. The box is an array, the type of cookie is Oreos, the order in which they sit in the box represents their position (a.k.a. it's index), and the values are the flavor.

Related

java 2d memory address

in java if we have:
int[][] x = new int[3][3];
the memory address of x is different from the memory address of x[0]. As x[0] gives the memory address of the first column. So the memory address of x[0][0] is different than the memory address of x[0].
are there any computer languages that store a 2d array as a matrix and not as an array of arrays?
would the address of x always be different from x[0] and the address of x[0] equal x[0][0]?
are there any computer languages that store a 2d array as a matrix and
not as an array of arrays?
Yes. Or, at least, there used to be.
There is the possibility of using an assembler language, where the programmer has extreme control over how arrays might be handled. But, let's assume the question is about high-level languages (>=3GL).
I don't know about modern version of Fortran, but the early versions of FORTRAN stored any array, including multi-dimensional arrays, in consecutive storage locations. So, for example, if you declared an array as INTEGER FOO (3,4,5), then FOO and FOO (1,1,1) would have the same memory address. FOO would occupy a block of 60 INTEGER sized locations. The compiler generates code to find, from the subscript values, the location of an element in a manner similar to what #Jesse described in a comment on the question. It's slightly different to allow for the fact that FORTRAN subscripts started at one instead of zero.
By the way, FORTRAN subscript are in opposite order of most other languages. In Java, C, C++, and COBOL, the major subscripts are to the left. In FORTRAN, they were to the right.
FORTRAN syntax didn't allow missing subscripts. So, continuing the example, something like FOO (2,3) would generate a compiler error.
Now, suppose there was the following method:
REAL FUNCTION MEAN (ARR, N)
INTEGER N, ARR (N)
REAL SUM
DO 400 I = 1,N,1
SUM = SUM + ARR (I)
400 CONTINUE
RETURN SUM / N
END
A programmer could it use to calculate the mean of the entire FOO array, or any part of it:
REAL ALLMEAN, LEVEL3MEAN, ROWMEAN
ALLMEAN = MEAN (FOO(1,1,1), 60)
LEVEL3MEAN = MEAN (FOO(1,1,3), 12)
ROWMEAN = MEAN (FOO(1,2,3), 4)
Suppose, for some strange reason, there was this:
AVGPART = MEAN (FOO (2,3,2), 20)
This would use 20 consecutive elements of FOO, even if those elements were in different rows or levels.
When I took a C++ course, someone didn't like having to type separate [x] subscripts for multidimensional arrays. Instead of foo [2][1][0], he would rather type something like foo.get (2,1,0), so wrote a convenience wrapper class for an array. Such code might still have foo [t][r][c] inside the wrapper class. Or, it could allocate a 1D array. Once the class was created, it allowed him to specify subscripts as arguments in a call to a method.
Code in Java to do that, using the 1D array option, might look like this:
public class Block {
// class for regular 3D Array
private int [] array;
private int rows, int columns, int levels;
public Block (int t, int r, int c) {
rows = r;
columns = c;
levels = t;
array = new array [ t * r * c];
}
public int get (int t, int r, int c) {
return array [ t * rows * columns + r * columns + c ];
}
public void set (int value, int t, int r, int c) {
array [ t * rows * columns + r * columns + c ] = value;
}
...
}

Get size of second dimension while first dimension is empty [duplicate]

Well, that might be a strange question, and maybe just because I'm not familiar enough with Java.
So, I declared a 2D int array:
int[][] arr = new int[0][10]
Now, as you can see, the second dimension's length is 10, while the first dimension's length is 0. I'm not sure how Java treats these kind of arrays, but the compiler doesn't produce any errors, which means it's a legit declaration.
Well, I passed the array to some function, and I want to retrieve from within the function, the length of the second dimension.
Of course something like:
arr[0].length
won't work. is there another way to do this?
The objects created by new int[0][10] and new int[0][20] are equivalent. There is no logical "second dimension" here. Effectively you're running something like this:
int[][] createArray(int d1, int d2) {
int[][] ret = new int[d1][];
for (int i = 0; i < d1; i++) {
ret[i] = new int[d2];
}
return ret;
}
Now if you translate that into your scenario, you'll end up with code which never reads d2.
If you want to represent a general-purpose rectangular array (instead of an array of arrays) you might want to consider creating your own type for it.
Arrays in Java, and most every other programming language, are zero-based. Consider this 2D array:
int[][] arr = new int[1][10];
This means that there is one row and ten columns in it.
Now, consider this array:
int[][] arr = new int[0][10];
This means that there are zero rows and (an irrelevant amount of columns) in it.
If you try to index into the second array, you'll find that you can't - an array of length zero has no starting point.
The compiler sees it as valid because you declared dimensions with it, but you won't be able to actually use it in any meaningful way in Java.
There is no such thing as the length of the second dimension. Consider:
int[][] arr = new int[10][10];
arr[5] = new int[42];
What is the length of the second dimension? 10 or 42?
No. It doesnt work this way. arr is an array with ten elements, each of which must be a reference of an int array (or null). That's all there is to say.

Adding two integer arrays

I have done some searching for this, however I haven't found anything specific to what I'm working on.
I'm trying to do addition with two arrays of integers. This alone isn't difficult, however, I'm having difficulty with a specific aspect.
The array size and array elements are determined by user input. Each digit must be greater than or equal to 0 and less than or equal to 9. The problem lies in the fact that if I initialize an array in my method, I must determine the size of the array when I initialize it. But if the user enters a series of numbers, such as 8, 0, 0, 0 for the first array, and 3, 0, 0, 0 for the second array, that would result in the sum[] being one integer bigger than either of the arrays initialized by the user. I don't want to do
int[] sum = new int[x.length+1]
because in the case of it not needing an extra element, I will get an ugly 0 where I don't want to see that. I'm not necessarily asking for a direct answer with code, but perhaps a bit of wisdom that will push me in the right direction. Thanks.
public static int[] addArrays(int[] x, int[] y){
int[] sum = new int[?];
int carryOver = 0;
int singleDigit = 0;
Just make the array originally the same size as the original (int[] sum = new int[x.length];. Then, if you need to expand the size of your array, set sum =Arrays.copyOf(sum, sum.length+1);, which will expand the size of your array to the necessary size.

Java setting two variables randomly and then setting a third

I am trying to figure out how to randomly assign two separate ints as variables. How to choose between them randomly makes sense (r.nextInt(02)), but I can not seem to find anything on how to assign one versus the other. I'm also trying to assign a third variable based on the sum of the first two, which I think I understand int c = (int a + b). But how do you set the third randomly each time? So that it could either be A, B or C?
Working on a game idea but I'm also constrained by the requirements that I've been given by one of the guys that I'm working under (who isn't available).
Try adding the 3 int A, B, C to an array and randomly selecting an index.
int[] numbers = new int[3];
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int index = rand.nextInt(3);
int yourNumber = numbers[index];

Java: Searching in an array of objects, for 2 specific object values

I'm doing a project in Java which includes (x,y) coordinates.
I have created a class of Cell which has protected integers X & Y;
Upon initialization, i do a for loop which sets an array of cell by multiplying the X & Y given by the user, say if X= 10 and Y = 10, i create an array of cells[100].
However, how can i search the array fast, without doing a for loop and checking each individual value very time?
Say I'm looking for the object that contains X=5 & y = 3.
I know i can go through with a for loop looking for object with values x and y, but i was wondering if there is a way to do a binary search and find "a bit faster" the object[i] that contains X=5 and Y=5.
Thank you very much.
The way to do this is to arrange the Cell objects in the array in a way so that there is a simple mapping from an X,Y coordinate to the Cell's index in the array.
For example, lets assume that X and Y go from 1 to 10. Suppose that we then arrange the Cells so that:
array[0] = Cell(1, 1);
array[1] = Cell(1, 2);
...
array[9] = Cell(1, 10);
array[10] = Cell(2, 1);
array[11] = Cell(2, 2);
...
array[99] = Cell(10, 10);
It should be easy to see that we can calculate the index of Cell(i,j) in the array and fetch the cell as follows:
public Cell getCell(Cell[] array, int i, int j) {
int index = (10 * (i - 1)) + (j - 1);
return array[index];
}
This is the approach that programming languages that support N-dimensional array types typically use to implement them.
This can be trivially modified to deal with cases where:
the constant 10 is something else
the matrix is not square,
the matrix has more than two dimensions
indexes run from 0 to N - 1 instead of 1 to N
etcetera
There are various other ways that you could represent 2-D matrices in Java. The simplest one is just using a Cell[][] cells which allows you to access cells as (for example) cells[i-1][j-1]. More complicated representations can be designed that use less space if the matrix is sparse (i.e. cells are missing) at the cost of more complex code and slower access times.
It sounds like (if you want to use binary search, anyway) you're setting element 0 to the Cell with x = 0, y = 0; element 1 to x = 0, y = 1, etc. If so you should be able to trivially compute the exact index of a given Cell:
// contains the Cell with x = desiredX, y = desiredY
yourArray[desiredX * X + desiredY];
If this is what you're doing, however, it'd probably be simpler to just make a 2-dimensional array:
yourArray = new Cell[X][Y];
...
yourArray[desiredX][desiredY];
the above two answers show the trivial method for getting the array index fast. id like to propose an alternative- use hashmaps with key, value pairings. the value could be objects. accessing hashmap elements run in constant time..

Categories