Java: 从数组实例化变量
Java: instanciate variables from array
在 Python 中,您可以执行以下操作:
myList = [1, 2, 3, 4]
a, b, c, d = myList
print a # -> 1
print d # -> 4
Java有没有办法做这样的事情? Better/faster 低于以下:
int[] myList= {1, 2, 3, 4};
int a = myList[0];
int b = myList[1];
int c = myList[2];
int d = myList[3];
您可以使用 Integer 类型的 ArrayList。
这类似于以下代码:
List<Integer> myList = new ArrayList<Integer>();
然后你可以使用.set(int where, int what)设置变量
myList.set(0,1);
或者您可以只附加 .add(int what)
myList.add(2);
然后你可以使用.get(int where)
获取变量
int a = myList.get(0);
int b = myList.get(1);
这会将变量 a 设置为 1,将变量 b 设置为 2,因为您将其附加到最后。这些 ArrayList 的优点是,您可以获得比 Array 更容易的变量,但是您需要更多的代码来添加它。所以它有利于代码中的大量不变变量。
不完全相同,但您可以使用逗号运算符接近它:
int[] myList= {1, 2, 3, 4};
int a = myList[0], b = myList[1], c = myList[2], d = myList[3];
在 Python 中,您可以执行以下操作:
myList = [1, 2, 3, 4]
a, b, c, d = myList
print a # -> 1
print d # -> 4
Java有没有办法做这样的事情? Better/faster 低于以下:
int[] myList= {1, 2, 3, 4};
int a = myList[0];
int b = myList[1];
int c = myList[2];
int d = myList[3];
您可以使用 Integer 类型的 ArrayList。
这类似于以下代码:
List<Integer> myList = new ArrayList<Integer>();
然后你可以使用.set(int where, int what)设置变量
myList.set(0,1);
或者您可以只附加 .add(int what)
myList.add(2);
然后你可以使用.get(int where)
获取变量int a = myList.get(0);
int b = myList.get(1);
这会将变量 a 设置为 1,将变量 b 设置为 2,因为您将其附加到最后。这些 ArrayList 的优点是,您可以获得比 Array 更容易的变量,但是您需要更多的代码来添加它。所以它有利于代码中的大量不变变量。
不完全相同,但您可以使用逗号运算符接近它:
int[] myList= {1, 2, 3, 4};
int a = myList[0], b = myList[1], c = myList[2], d = myList[3];