Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Java "pointers" work?

Tags:

java

pointers

Lets say this is the C++ code:

void change(int& x){
    x++;
}

or

void change2(int* a){
    *a++;
}

Both will change the global x, right?

So how can I do something like that in java?
Specifically, I want to point to a Vector object

But since Java has no pointers, I'm not sure what to do.
From searching the internet I saw people saying that Java does that in some other way, but I haven't found any real example.

Thanks for help!

like image 514
SmRndGuy Avatar asked Apr 15 '12 08:04

SmRndGuy


2 Answers

In Java, instead of pointers you have references to objects. You cannot pass a primitive type by reference, but you can wrap a primitive type inside an object and then pass a reference to that object.

Java provides the type Integer which wraps int, however this type is immutable so you cannot change its value after construction. You could however use MutableInt from Apache Commons:

void change(MutableInt x) {
    x.increment();
}

The change to x will be visible to the caller.


Specifically, I want to point to a Vector object

When you write Vector v = ...; you are assigning a reference to a vector to the variable v. A reference in Java is very similar to a pointer. References are in fact implemented internally using pointers.

Java uses pass by value. When you pass a vector to a method, you are actually copying a reference to that vector. It does not clone the vector itself. So passing a reference in Java is very similar to passing a pointer in C++.

like image 119
Mark Byers Avatar answered Sep 18 '22 01:09

Mark Byers


With Java you cannot pass primitive types like int by reference, they are passed only by value.

The only things you can do is to find artifices to do that, because instead Objects are passed by reference. Here two examples.

Use an array of single value, like this

int[] value = new int[1];
value[0] = 2;

// call a method
obj.setValue(value);

// and in setValue
public void setValue(int[] value) {
  value[0] = 5;
}

Or second approach use an holder class:

public class Holder<T> {
  public T value;
  public Holder(T value) {
    this.value = value;
  }
}

// then use it in this way
Holder<Integer> h = new Holder<Integer>(2);

obj.setValue(h);

// and in setValue
public void setValue(Holder<Integer> h) {
  h.value = 5;
}

In this case I use an holder class implements with generics but you can have a simple holder too, only for integer. For example:

public class IntHolder {
  public int value;
  public IntHolder(int value) {
    this.value = value;
  }
}
like image 32
dash1e Avatar answered Sep 22 '22 01:09

dash1e