Can you operate on Arrays in Java like in Matlab?
I was wondering whether there was a way to do the following, without writing a function or a for loop:
int[] ma = (3,4,4,5,6,7);
ma += 5;
thus, adding 开发者_如何学Go5 to all elements in the array. Matlab allows for such a convenient shortcut.
Short answer: No you can't. You need to write a loop to do it.
In a word: no. Java has no operations like that. But there's nothing to stop you from writing a method add()
that takes an array and an int and adds the int to every element in the array. Write subtract()
, multiply()
, etc, and you'd have a nice little library for your own use.
If you need this a lot looking into Scala might be an option. Scala also runs on the JVM, and has things like folds, which allow you to define these kind of things in very little code.
However, it is a functional language, which requires a different way of thinking than traditional (iterative) programming.
Java provides a number of collection classes with functionality similar to what Matlab provides for arrays. The closest match would be java.util.ArrayList
, which is backed by an array. You can use the add()
method to append items to the collection, instead of a +=
operator. ArrayList
exports a number of interfaces which make it compatible with many of the methods and classes in other java packages.
精彩评论