, Если моя интуиция корректна , и Вы на самом деле хотите изменить среду в пользу порожденного (разветвленного) подпроцесса (Runtime.getRuntime().exec()
), затем использовать ProcessBuilder вместо exec()
. Можно создать пользовательскую среду через Ваш ProcessBuilder
экземпляр среда () метод.
, Если это не , что Вы пытаетесь достигнуть затем доброжелательного игнорирования этот ответ.
ОБНОВЛЕНИЕ
ответ на Ваши три обновленных, конкретных вопроса следующие:
System.getenv()
в той же JVM или обоих. setenv
или ее определенный для платформы эквивалент через JNI. Можно также использовать чрезвычайно замысловатый метод от [1 119] точка 2 ниже, который работает на любой процесс (если у Вас есть полномочия.) Однако знать, что в большей части JVMs это изменение никогда не могло бы отражаться в значениях, возвращенных System.getenv()
, поскольку среда, как правило, кэшируется при запуске виртуальной машины в java.util.Map
(или эквивалентный.) System.java
в том, какой бы ни распределение JVM Вы будете использовать для развертывания), можно попытаться взломать реализацию (через порядок загрузки класса, отражение , или инструментарий .) В случае v1.6 JVM SUN, например, кэшем среды управляют недокументированным ProcessEnvironment
класс (который можно исправить.) gdb
, будет приостановлен за ненулевое количество времени. Примечание, что все методы выше, за исключением одного вовлечения ProcessBuilder
, являются хрупкими, подверженными ошибкам, непортативными до различных градусов и подверженными условиям состязания в многопоточных средах.
How exactly JavaScript arrays are implemented differs from browser to browser, but they generally fall back to a sparse implementation - most likely the same one used for property access of regular objects - if using an actual array would be inefficient.
You'll have to ask someone with more knowledge about specific implementations to answer what excatly triggers the shift from dense to sparse, but your example should be perfectly safe. If you want to get a dense array, you should call the constructor with an explicit length argument and hope you'll actually get one.
See this answer for a more detailed description by olliej.
Yes, they are. They are actually hash tables internally, so you can use not only large integers but also strings, floats, or other objects. All keys get converted to strings via toString()
before being added to the hash. You can confirm this with some test code:
<script>
var array = [];
array[0] = "zero";
array[new Date().getTime()] = "now";
array[3.14] = "pi";
for (var i in array) {
alert("array["+i+"] = " + array[i] + ", typeof("+i+") == " + typeof(i));
}
</script>
Displays:
array[0] = zero, typeof(0) == string
array[1254503972355] = now, typeof(1254503972355) == string
array[3.14] = pi, typeof(3.14) == string
Notice how I used for...in
syntax, which only gives you the indices that are actually defined. If you use the more common for (var i = 0; i < array.length; ++i)
style of iteration then you will obviously have problems with non-standard array indices.
Вы можете избежать этой проблемы, используя синтаксис javascript, разработанный для такого рода вещей. Вы можете рассматривать его как словарь, но синтаксис «for ... in ...» позволит вам получить их все.
var sparse = {}; // not []
sparse["whatever"] = "something";
Javascript objects are sparse, and arrays are just specialized objects with an auto-maintained length property (which is actually one larger than the largest index, not the number of defined elements) and some additional methods. You are safe either way; use an array if you need it's extra features, and an object otherwise.