Hey so I'm wondering how can I make AtomicInteger a two dimensional array, From what I've found on javadocs AtomicIntegerArray is only single dimension.
int[] newArray = new int[100];
AtomicIntegerArray atomicarray = new AtomicIntegerArray(newArray);
Which creates a AtomicIntegerArray of size 100. But I would like an atomicarray with two dimensions. I've tried doing..
AtomicInteger[][] atomicArray = new AtomicInteger[100][100];
atomicArray[00][00].set(1);
But I am met with..
java.lang.NullPointerException at nz.ac.massey.threadpool.MyClass.(MyClass.java:20)
So any ideas? thanks! :)... I haven't done much work with Atomic variables before.
if this isn't possible how can I minimic a regular primitive integer two dim array into a AtomicInteger two dim array?
Just create a one-dimensional array of length m * n, you then need a function that maps a pair of integers (i, j) to one integer. i * n + j is a good start. Assuming m is the number of rows and n the number of columns.
It is a good idea to keep all of your integers inside the AtomicIntegerArray. Or you'll have to deal with concurrency your self.
You need to instantiate all of the positions in the matrix before accessing them, something like this:
atomicArray[i][j] = new AtomicInteger();
Or this, if you want to initialize each atomic integer in a certain initial value:
atomicArray[i][j] = new AtomicInteger(initialValue);
That, for all i,j positions in the matrix. Normally you'd do this using a couple of nested for loops:
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
atomicArray[i][j] = new AtomicInteger();
}
}
Related
Enhanced for loops are weird. Why does
int size = 10;
Random random = new Random();
int[] scores = new int[size];
for (int score : scores) {
scores[score] = random.nextInt(size);
}
System.out.println(Arrays.toString(scores));
Give me a mostly empty array where only the first element is the random number,
whilst:
int size = 10;
Random random = new Random();
int[] scores = new int[size];
for (int i = 0; i < scores.length; i++){
scores[i] = random.nextInt(size);
}
System.out.println(Arrays.toString(scores));
gives me what I want: a 10-element array composed of random digits?
I thought the two loops were substitutions of each other; but when it comes to the Random(), it's only the first element that gets altered?
The enhanced for loop:
for (int score : scores)
iterates over the values of the array, not the indices.
When you instantiate the array with int[] scores = new int[size], The values are all initialized to 0 by default.
Therefore:
scores[score] = random.nextInt(size);
is always:
scores[0] = random.nextInt(size);
When you need to modify an array, you should use the traditional for loop, which iterates over the indices.
These are different constructs. Essentially with the first loop, you are saying "go get all of the elements of scores and loop over them. You don't get the index, you get the actual values which will always be0` in your case!
for (int score : scores){
// score is always 0!
scores[score] = random.nextInt(size);
}
Your second loop, as you've figured out, gives you the index (i) rather than the value in the scores array.
it seems that you have a misconception about the enhanced loop in Java, because it is a foreach loop and iterates over the values of the array, not over the keys:
Look at the following example
String[] my_string_array = new String[]{"Dog","House","Cat"};
for(String s: my_string_array){
System.out.println(s); //prints "Dog", then "House", then "cat"
//s equals one entry of the Array
}
In your example, every entry of the array is 0, because this is the default value for integers.
So in each repetition of your array, the following happens
scores[0] = random.nextInt(size);
I hope you understand the problem with your first code.
Just use the first one, it is working and best practise.
You have two different loops actually,
for (int score : scores){
and
for (int i = 0; i < scores.length; i++){
First one gives the value of array (not an index of specified array) whereas second gives the index. As said, the meaning changes for below code
scores[score] = random.nextInt(size);
So, imagine your array has value 1,2,5, so you would basically accessing index 1, 2 and 5 in first loop, on the other hand, second loop assigning value to specific index, which goes with 0, 1 and 2.
Since scores was initialized with default values 0, so in each iteration, it was updating value at the 0th index.
Assume that I already have a 2D int value[i][j]. This works well and I can store a single int in each index. Now I want to add a second array int data[i][j] so I can store multiple int data in it. Am I approaching it correctly?
For example in a Sudoku situation:
value[0][0] = 0
But in an other grid I have all possible values in each index
data[0][0] = {1,2,3,4,5,6,7,8,9}
Is it possible to do that? If so what should I do with my data? I'm really confused about arrays, multi-dimensional arrays, ArrayLists, etc. I'm unsure which to use.
For example:
Values {1,2,3},{4,5,6},{7,8,9}
In an 3x3:
1,2,3
4,5,6
7,8,9
Data{1,2,3,4,5,6,7,8,9}
Which I want to store it now in each grid and will have a method to remove from that list in later steps because I'm cancelling those possibilities in that grid. And the data in data{} doesn't have to be shown to the user.
I hope this will clear to some extent
Internally, Java stores 2 dimensional arrays as an array of arrays:
Suppose you have
int [][] nums = new int[5][4];
The above is really equivalent to a 3-step process:
int [][] nums;
// create the array of references
nums = new int[5][];
// this create the second level of arrays
for (int i=0; i < nums.length ; i++)
nums[i] = new int[4]; // create arrays of integers
Simply use boolean[] for possible choices. You could use Set (http://docs.oracle.com/javase/7/docs/api/java/util/Set.html), but for a small pool of fixed size with boolean options only, Set is an overkill (mainly due to code overhead).
Next thing is, that the basic principle of OOP (and Java is, or at least should be OOP) is that you should group data into objects/classes based on their functionality. If you're trying to aggregate a cell in a grid, you should create a grid (2D array) of objects, not a couple of int or boolean (or whatever) arrays.
First create a class, e.g.
class Cell {
final int POSSIBILITES = 9;
int actual_value;
boolean[] possible_values = new boolean[POSSIBILITES]; // for each number
Cell( int actual_value ) {
this.actual_value = actual_value;
for( int i = 0; i < POSSIBILITES; i++ )
possible_values[i] = true;
}
}
and then initialize/instantiate an array of objects
//...
final int X_SIZE = 9, Y_SIZE = 9;
Cell[][] cells = new Cell[X_SIZE][Y_SIZE];
for( int i = 0; i < X_SIZE; i++ )
for( int j = 0; j < Y_SIZE; j++ )
cells[i][j] = new Cell( somevalue );
//...
And then access them by, for example
//note: it's more proper to use getter/setter pattern, so this is only a crude example
if ( cells[3][6].actual_value = 7 )
do_something();
cells[1][2].possible_values[0] = false; // we're numbering from 0 to 8, so value 1=> index 0, 2=>1... 9=>8
cells[1][2].possible_values[4] = true;
Yes, it is possible. For that I'd recommend a boolean[][][] where, for example, theArray[6][3][8] is a boolean indicating whether the number 8 is included in the cell at row 6, column 3.
In Java you can do this
int[][] i = new int[10][];
Does this just create 10 empty arrays of int? Does it have other implications?
It creates a 10-entry array of int[]. Each of those 10 array references will initially be null. You'd then need to create them (and because Java doesn't have true multidimensional arrays, each of those 10 int[] entries can be of any length).
So for instance:
int i[][] = new int [10][];
i[0] = new int[42];
i[1] = new int[17];
// ...and so on
Executing your code creates an array of size 10, each element of which can hold a reference to a int[], but which are all initialized to null.
In order to use the int[]s, you would have to create new int[] for each of the element, something like this:
for (int n = 0; n < 10; n++)
i[n] = new int[10]; // make them as large as you need
Yes, it does; however, each of those arrays are null. You have to then initialize each of those sub-arrays, by saying int[10][0] = new int[MY_SIZE], or something similar. You can have arrays with different lengths inside the main array; for example, this code would work:
int[][] i = new int[10][];
for(int ind = 0; ind<10;ind++){
i[ind]=new int[ind];
}
It is just an array of arrays.
Here you create ten new int[0] arrays. You have to manually initialize it, it's useful when you don't need square matrix:
int[][] array = new int[10][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[i];
}
If you need square matrix you can do:
int[][] array = new int[10][10];
And it will be initialized with default values.
That is just the declaration, you need to initialize it. The 10 arrays would be null initially.
I have the following code generating 5-digit random numbers and adding them to an ArrayList. These numbers however must be unique ids.
for(int i = 0; i < myArr.length; i++) {
int id = (int) (Math.round(Math.random() * 89999) + 10000);
idArr.add(id);
}
I'm trying to work out how I could check to see if the number was already in the array before adding it but I can't get my head around the best way to do this.
Don't use an (Array)List, use a Set:
Set<Integer> set = ...;
while (set.size() < myArr.length) {
set.add(yourRandomNumber);
}
Use an ArrayList instead of an array. That way you would just need to use ArrayList#contains(obj) method to test whether the id is already in the ArrayList or not.
Or, you can just work with a HashSet, which will work faster with its HashSet#contains() method.
You can create a Set of the numbers. E.g.:
Set<Integer> intSet = new HashSet<Integer>();
while(intSet.size() < myArr.length) {
intSet.add(getNextRandomInt());
}
Then yo can do anything with that Set.
So, if you need an array, just call:
Integer[] intArray = intSet.toArray(new Integer[myArr.length]);
or, if you need an ArrayList or int[] array:
// ArrayList:
List<Integer> ints = new ArrayList<Integer>();
ints.addAll(intSet);
// int[] array:
int[] intArray = new int[myArr.length];
for( int i = 0; i<intArray.length; ++i) {
intArray[i] = int.get(i);
}
Anything which involves looping until you find enough unique random numbers is never guaranteed to complete. It's possible, if extremely unlikely, that the random number generator will never output enough unique numbers in a reasonable amount of time.
(I know this will never happen in practice, but it's a theoretical possibility.)
A safe alternative is to choose one random number, and then increment it in a loop until you have enough numbers.
int n = new Random().nextInt(89999 - myArr.length) + 10000;
for (int i = 0; i < myArr.length; i++) {
idArr.add(n++);
}
How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);