2

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 5 to all elements in the array. Matlab allows for such a convenient shortcut.

zellus
  • 9,617
  • 5
  • 39
  • 56
noisebelt
  • 940
  • 2
  • 9
  • 20
  • In C# you can overload operators and thus have such syntax, I am using this feature extensively. In C# `x+y+z` would be in Java `a.Add(b.Add(c))` – Mikhail Poda Sep 25 '11 at 17:51

4 Answers4

3

Short answer: No you can't. You need to write a loop to do it.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
1

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
1

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.

Jesse van Bekkum
  • 1,466
  • 3
  • 15
  • 24
  • I'm not certain as to why one would ever "need" something like this. It is simply syntactical sugar; you can always just write a loop or a new method to do the same thing. – Ed S. Sep 25 '11 at 17:59
-2

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.

CurtisB
  • 214
  • 1
  • 5