Phonon Phonon - 1 year ago 91
Java Question

Equivalent of incrementing a C/C++ pointer in Java?

I do have somewhat of a feeling that people will try to beat me over the head and say "You're not supposed to do that!" (and I'm quite aware of this fact); nevertheless, here's my problem:

Suppose you've got the following C++ code:

I think I haven't shown enough of what I'm trying to do, even though most of the answers were excellent. So here's an edited version of my code. The heart of it is that a every iteration I still need to use an array of vales that happens to be a sub-array of

, not just a single value at an index:

unsigned int n = 2000; // or any other number for that matter
double * x = new double[n];
double resultArray;

// fill array with meaningful data
// do all kinds of initializations

for( int i=0 ; i<someNumber ; ++i ){ //someNumber ~ 1900

// do some stuff

for (j=0 ; j<someSmallerNumber ; ++j){ //someSmallerNumber ~ 15
resultArray[j] = x[j] * someFunction(resultArray[j]);

++x; //increment pointer to the first element of the array

// do some more stuff


EDIT: The reason I use
in the outer loop is that if I used
instead of just
I would perform many more additions per iteration and this is an algorithm heavy on algebra, so I'm trying to squeeze some performance out of it.

I would like to point out that my algorithm never tries to read non-existent memory. This is simply a speed of processing issue where I'm trying not to recalculate current array index more times than I have to. This runs perfectly well, and I'm happy with it.

Now I'm trying to implement a similar algorithm in Java (and Java in not quite my area of expertise). I do know, however, that Java does not really give you access to pointers and handles everything as an Object. My question is, of course, is there an efficient way to perform an equivalent of
is an address of the first element of an array in Java? Is there perhaps a way to remove the first element of an array instead? Are there good fast algorithms to look at if it's not a part of built-in Java array manipulations?

Thanks in advance! = )

Answer Source

Java is not C++. The things you do in C++ to gain speed do not necessarily apply to Java. This is one of those cases.

Using the for(int val : x) in Java will not, as some people suggest, give you any advantage over:

for(int i = 0; i < x.length; i++)
    int val = x[i];

Reference here;

What people are saying here about the VM is free to make optimizations at runtime is correct.

So, yes, you do need to be beat over the head a little :-). While Java and C++ look similar, what you do in one is not what you would do in the other in all cases: to write good Java, you must think in terms of Java; for C++, you must think in terms of C++.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download