#### Archived

This topic is now archived and is closed to further replies.

# [java] Return more than 1 data

This topic is 5569 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

In Java, it seems I can only return one piece of information via the return statement. Is there anyway to return two piece of info, ie like in C, you can use pointers to return data through the parameters.

##### Share on other sites
Not sure exactly what you mean about c with that wording, sorry it just confused me a bit. However, you can return whatever data you want in a java return statement. Just wrap the data you want to return into a class, and return that. A return statement can return ANY data type, built in or user defined. So if you want to return a matrix or something of the like, write a class for it, and return an object of that class.

##### Share on other sites
i believe he is talking about passing by reference using pointers so that when you modify the data that the pointer points to the changes are then visible outside the scope of the function. in java all objects are passed by reference so if you change them in a function they get passed to, they will be changed outside as well. the basic datatypes like int and stuff are passed by value so this is not the case but you can use the object version of these (ie. Integer instead of int) and its relatively trivial to convert between these (if you look at java.sun.com you can find out about them if you didn''t know). so if you use these objects then they will be passed by reference aswell.

##### Share on other sites
Thanks for that, its just I was hopping to not create another class for that purpose. Say if I just want to return 2 or 3 integers at the same time from a method.

Sorry about the wording, I was worried I wasnt making myself clear. In C (or C++) you can send into the parameter the address of a data type to store it in.
i.e.

int getInfo( int& a ) {
a = 10;
return 5;
}

Now if I did this:

int v1;
int v2;
v1 = getInfo( v2 );

v1 would be 5, and v2 would be 10, thus from one method I get two results.

##### Share on other sites
quote:
Original post by necromancer_df
i believe he is talking about passing by reference using pointers so that when you modify the data that the pointer points to the changes are then visible outside the scope of the function. in java all objects are passed by reference so if you change them in a function they get passed to, they will be changed outside as well. the basic datatypes like int and stuff are passed by value so this is not the case but you can use the object version of these (ie. Integer instead of int) and its relatively trivial to convert between these (if you look at java.sun.com you can find out about them if you didn''t know). so if you use these objects then they will be passed by reference aswell.

I heard it was pass by reference and I actually tried it but it didn''t seem to work. As a example:

bool getColor( Color c )
{
if( m_c==null ) return false;
c = m_c;
return true;
}

Unfortuantely, when I used:

Color aColor;
getColor( aColor );

aColor will always be the default black for some reason. I have made sure that the method will succeed (m_c is red). I''ll try again and see what happens.

##### Share on other sites
quote:
Original post by AndyTang
I heard it was pass by reference and I actually tried it but it didn''t seem to work. As a example:

bool getColor( Color c )
{
if( m_c==null ) return false;
c = m_c;
return true;
}

Unfortuantely, when I used:

Color aColor;
getColor( aColor );

aColor will always be the default black for some reason. I have made sure that the method will succeed (m_c is red). I''ll try again and see what happens.

That won''t work.
The function getColor is passed the *value* of the pointer aColor. Hence it can modify properties of aColor or call methods an it will stick, however modifing the pointer value passed will do nothing (the value of a pointer to an object was passed, not a value of a pointer to a pointer to an object)

##### Share on other sites
In Java, everything is passed by value. There is no pass by reference in Java. However, whenever you use object types, the variables you deal with are references to objects rather than objects themselves. When you pass these references to methods, they are copied by value. Therefore, when you pass an object to a method such as, say, doSomething(Integer x), and call it with doSomething(i), the local variable x will hold a reference to the same object that i refers to, and since you are holding a reference, you can change the object that they both refer to. However, if you try to assign to x, you will assign a new object to the local reference. You have absolutely no way of assigning to the reference i, because it is copied by value (the value of the address hidden inside it, I should think). In C you could get around this by passing a pointer-to-a-pointer; in Java the only way to get around it is by enclosing the reference inside of an object (you could, for instance, put i as an element of an array; the array would then be passed by reference, and you could alter it).

There may be more elegant solutions to the problem, but in a recent assignment for Principles of Programming Languages, that was the best hack I could come up with ...

##### Share on other sites
Java passes all paramaters by value and not by reference.

If you want to modify something with java, you either have to write function that does it within the class, or return the new value.

IE,

aClass.SetVariable(variable to set)
// changes the value of aClass

or aClass = changeColor(aClass);
//assigns aClass the value of aClass after the changeColor method has been acted upon it. not that changeColor must be static in this case

[edited by - D_Y on November 19, 2002 12:15:48 PM]

[edited by - D_Y on November 19, 2002 12:16:52 PM]

##### Share on other sites
OK,
D_Y is plain wrong.
Miserable is over-complicating the issue.

AndyTang, you are trying to directly convert what you are used to doing in C in to Java, it won''t work!
This example,

bool getColor( Color c )
{
if( m_c==null ) return false;
c = m_c;
return true;
}

in C is roughly equivalent to,

Color* m_c;
bool getColor(Color* c)
{
if (m_c==NULL) return false;
c=m_c;
return true;
}
This obviously isn''t what you are trying to do!!
Unfortunately there is no equivalent to *c=*m_c (as you would like to do), as you don''t have this kind of control in Java.

There is no way to do exactly what you are trying to do, but before you jump up and say, ''Java is crap, you can''t even do this!?!?'' let me say that Java is in many ways a completely different language to C++.

The reason C programmers always try to do this kind of thing in Java when it isn''t the best way is because there is a much more complicated sense of ownership of memory in C/C++. In your example, the calling method has ownership(we''ll assume it isn''t higher up the call stack) of the memory pointed to by the variable ''c'', this doesn''t matter then if this memory is on the stack or in the heap, the calling method can deal with this kind of thing. But you haven''t got this problem in Java, all objects are created equal, and are on the heap. So, doing this kind of thing in Java, you would just have,

public Color getColor()
{
return m_c;
}
Note that this only returns a shallow copy, and not a deep copy.

Now onto the problem you were originally asking about, you can have more than one return value in Java, but it is very rarely used, don''t ask me why this is the case, but due to the design of the language, you don''t need to use it as much. But as an example, you would do something like,

public class myClass {public myClass(int initialValue) {i1=initialValue}public int i1;}public void method1() {myClass c=new myClass(10);int originalValue=method2(c);}public int method2(myClass c) {int originalValue=c.i1;c.i1=5;return originalValue;}

Hopefully that will clear some things up, but remember, despite what people say, Java is sometimes a very different language to C++.

Jiim Jonez
---
www.javage.net

##### Share on other sites
quote:
Original post by Jiim
Hopefully that will clear some things up, but remember, despite what people say, Java is sometimes a very different language to C++.

Thanks for your answer and everyone else. I know that Java is a different language (much like javascript is really a completely different language to Java although they have their similarity. I was just wondering if there was a way.

The problem I had was that I needed to return two pieces of information from an algorithm. I could have execute the algorithm twice to retrieve each data separately but I wanted to be efficient.

##### Share on other sites
quote:
Original post by Jiim
Hopefully that will clear some things up, but remember, despite what people say, Java is sometimes a very different language to C++.

Thanks for your answer and everyone else. I know that Java is a different language (much like javascript is really a completely different language to Java although they have their similarity. I was just wondering if there was a way.

The problem I had was that I needed to return two pieces of information from an algorithm. I could have execute the algorithm twice to retrieve each data separately but I wanted to be efficient.

##### Share on other sites
There''s no problem here. Follow these simple steps, and everything will be just fine:

1) Call a separate method to convert the data to Strings. This should look something working with an assembler ("numberOfWeaselsOnScreen", "feralWeaselRabidityLevel", "weaselAttachedToNeckOfVictim")

2) Loop through the data items, adding a prefix to each, to describe its data type. ("int numberOfWeaselsOnScreen")

3) Concatenate all of these strings into a single String

4) Call another method to cycle through each character, encoding it for security purposes. Encrypt the key using a separate algorithm, and append that to the encoded String.

5) Open a stream, and write the String to file.

6) Return the filename as a String to the original calling method.

7) The calling method should then call another method to load the file.

8) Call a decryption method, which begins by creating a substring from the last eight characters of the String. This is the encryption key.

9) Decrypt the key using the proper algorithm.

10) Remove the final eight characters of the String.

11) Use the key and a different algorithm to decrypt the String.

12) Call a method to cut the String into separate character arrays. The String should be cut once for every second blank space character, then that next space should be removed from the String.

13) Parse each substring into its given data type. "int numberOfWeaselsOnScreen" should be converted to an int with the name numberOfWeaselsOnScreenTemp.

14) Loop through the resulting data types, checking to see whether a variable with the given name exists. If so, the data is global, and the new value may simply be assigned to the original variable.

15) If the variable is not global in scope, it is safe to create a new variable with the original name. "weaselAttachedToNeckOfVictimTemp" may be converted to an Image named weaselAttachedToNeckOfVictim.

16) Delete the file, for security purposes.

17) Dispose the String and all temporary variables.

18) If necessary, edit the log files of the host computer, server, etc.

19) Use the returned data.

That''s all there is to it! You may take a performance hit, due to the overhead involved. But by using this technique, you can return any number of values, and any types you like.

It''s not pretty, but what this technique lacks in speed it makes up for in simplicity. Good luck!

Jonathon
quote:
"Mathematics are one of the fundamentaries of educationalizing our youths." -George W. Bush

"When a nation is filled with strife, then do patriots flourish." - Lao Tzu

##### Share on other sites
Parameter passing in Java: http://www.yoda.arachsys.com/java/passing.html

As for the question at hand - there is a hackish workaround:

  Color[] color = new Color[]{ Color.black }; //color[0] is now blackgetColor( color ); //color[0] is now red - this can be expanded to any number of paramspublic void getColor( Color[] color ){   color[0] = Color.red;}

God puts an apple tree in the middle of the Garden of Eden and says, do what you like guys, oh, but don''t eat the apple. Surprise surprise, they eat it and he leaps out from behind a bush shouting "Gotcha." It wouldn''t have made any difference if they hadn''t eaten it... because if you''re dealing with somebody who has the sort of mentality which likes leaving hats on the pavement with bricks under them you know perfectly well they won''t give up. They''ll get you in the end. -- Douglas Adams

##### Share on other sites
jeez, you can always use an array. something like

    public int[] someMethod(int x) {  int y = 2*x;  int z = 4*x;  int[] temp = new int[2];  temp[0] = y; temp[1] = z;  return temp;}

and then somewhere else

  int[] result = someMethod(3);int val1 = result[0];int val2 = result[1];// and so on..

edit: typos
_______________________
http://mill.3dfxsweden.net

[edited by - mill-o on November 20, 2002 2:34:22 PM]