• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sum up two arrays  RSS feed

 
John Joe
Ranch Hand
Posts: 439
3
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this a valid way to sum up two arrays? What it mean by the operator + is undefined for the argument....

 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot overload operators nor “lift” them to apply to arrays. A few operators however are already overloaded and you can't un‑overload them, e.g. & on booleans and + on Strings.

You would have to iterate the two arrays and sum them. Or (Java8 only) you can create two IntStreams joined with a flatMap call and them use sum().
 
John Joe
Ranch Hand
Posts: 439
3
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You cannot overload operators nor “lift” them to apply to arrays. A few operators however are already overloaded and you can't un‑overload them, e.g. & on booleans and + on Strings.

You would have to iterate the two arrays and sum them. Or (Java8 only) you can create two IntStreams joined with a flatMap call and them use sum().


How shoud I write in older to add them up?

(Object[] array) // assuming it holds
[2,3]

Object[] array4 // [0.0] and [0.1]
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Joe wrote:
How shoud I write in older to add them up?

(Object[] array) // assuming it holds
[2,3]

Object[] array4 // [0.0] and [0.1]


The Java implicit casting and autoboxing mechanisms will not help you here. You are responsible for verifying the type, and explicitly casting and boxing/unboxing as needed. You also need to iterates the arrays.

Henry
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot directly apply the + operator to an Object. You can consider applying it to a Number, so you might be able to get away with two Number[] arrays. If you use boxing and unboxing, then Integer extends Number so you should find that an Integer[] is a subtype of a Number[] array.

You cannot apply such things to primitive arrays.
 
Liutauras Vilda
Sheriff
Posts: 4923
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Beside all mentioned points, using "for" loop in this way, would work only if two arrays would be the same length (2).
You should think about the cases if 1st array would have 2 elements in it, another - 1 or 3 for example.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!