Reputation: 12395
-In JavaScript you can use a generic value type var
-In Java you must use explicit value types double
, int
, String
etc
-In JavaScript the Array can have also heterogeneous values.
-In Java an array can have only values of the same kind,(for example all double or all String).
What happen if I write in JavaScript?
var test[]=new Array();
test[1] = 16.98;
test[2] = 8.33;
test[3] = 5.31;
test[10] = 5.04;
The NOT-ASSIGNED index values are set to 0
, to null
, or to blankspace
?
Since all primitive values have a specific null value, for boolean false, for int 0 etc. If I want to port the above array form JavaScript to Java without errors I should know exactly the JavaScript policy for not assigned index values of the array.
Is correct to port the above sample in Java in this way?
double test[]={0, 16.98, 8.33, 5.31, 0, 0, 0, 0, 0, 0, 5.04}
Upvotes: 1
Views: 4011
Reputation: 14544
They won't be set to anything. If you read them, you will get back undefined
.
To port to Java, use a HashMap<Integer, Double
:
Map<Integer, Double> sparseArray = new HashMap<Integer, Double>();
sparseArray.put(1, 16.98);
sparseArray.put(2, 8.33);
sparseArray.put(3, 5.31);
sparseArray.put(10, 5.04);
System.out.println(sparseArray.get(10)); // 5.04
System.out.println(sparseArray.get(6)); // null
The difference between this and Javascript is that Javascript will keep track of the largest index (in the length
property). If you need the same behavior in Java, you will need to implement it yourself.
Upvotes: 2
Reputation: 1519
JavaScript has a special value used when you request something that does not exist: undefined
. Java does not have an equivalent construct. That is your first problem.
Your second problem is that you are not using the correct data structure in Java when porting your code if you want to obtain the exact same effect. JavaScript arrays are sparse arrays. In the example you posted above, the array has no memory allocated for indices 4 through 9. Requesting them will result in your program receiving undefined
.
If you absolutely want to have the same sparseness behavior, you will need to use a Map
.
Upvotes: 2