0

I'm using a class and main of my own devising. To do the simulation I need to, I need to determine what object from an array of identical objects contains the greatest of a certain private field. For example,

Robot[] set = new Robot [7];
//initialize here, and do other stuff

At this point, I need to figure out which object within Robot has the greatest value of a certain field, which we'll call myBeepers, and tell that Robot to run a method, which we'll call dropAllBeepers. And that is where the problem lies, because

  1. How do I call Math.max for something like this, and then call the corresponding object?
  2. I need extremely efficient code (in terms of methods called, not execution time. It's complicated, but in short, I need to call as few methods as possible), and a for-loop would cost me an extreme amount of memory, so that's out of the question.

In short, how do I get this down to a single line? Something like:

Math.max (set.getBeepers()).dropAllBeepers();

Except this doesn't work because Math.max turns in a variable, not the object.

intcreator
  • 4,206
  • 4
  • 21
  • 39
Siris
  • 13
  • 4
  • A for loop on an array of length `7` would cost you an extreme amount of memory? How? – Mshnik Mar 08 '16 at 03:22
  • I'm using this for a competition that uses a unique way of determining code size. Obviously, it wouldn't take up an extreme amount of memory in real coding, but it does in their system. – Siris Mar 08 '16 at 13:06

3 Answers3

0

The best bet would be to do something in the Robot class , something like this :

public static int maximum = 0;

public void setBeepers(int n){
   if (n>maximum){
       maximum = n;
   }
  this.n = n;
}

In that way maximum would always contain the maximum value and you won't need any other function or for loop.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

Assuming Robot implements Comparable on myBeepers field.

Robot[] sortedRobots = Arrays.sort(robots);
sortedRoborts[sortedRobots.length -1].dropAllBeepers();
Sanj
  • 3,879
  • 2
  • 23
  • 26
-1

tried looking at reflection API ? How do I read a private field in Java?

if you want to have totally external solution you can use comparator API with reflection API and sort the list.

if you can change the code of class implement compareTo method

Community
  • 1
  • 1