When I want to speedup part of codes, I use a lookup table instead of a function. In other languages I use global arrays to do this job. I pre-calculated all return values and put them in an array.
Here is an example of a function :
public static int Box(int c) { /* c value range is 0-80 */
return ((c / 9) / 3) * 3 + ((c % 9) / 3);
}
I could instead use an array like this :
int Box[] = {0,0,0,1,1,1,2,2,2,0,0,0,1,1,1,2,2,2,0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,3,3,3,4,4,4,5,5,5,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,6,6,6,7,7,7,8,8,8,6,6,6,7,7,7,8,8,8}
Java doesn't have global arrays!
What would be the best way way to do this so I can access these values?
You can still use global variables. You just need to put them in a class.
public class PrecalculatedValues{
public static final int BOX[]={0,0,0,1,1,1,...};
}
You can access BOX later in your code like so:
public static void main(String[] args) {
System.out.println(PrecalculatedValues.BOX[0]);
}
In Java, the equivalent of globals are public static variables. If you want to make the static variable immutable, then it should also be declared as final.
Also, the naming convention in Java for static variables is to capitalize the entire name, and separate words with underscores (ex: SOME_BOX).
Using your example above, you can do:
public static final int[] BOX = {0,0,0....};
Though it is possible to use a lookup table it is completly unnecessary in this case, since the equation can be calculated without branches in a couple of cycles.
When using arrays as a lookup table branches will become necessary because of the ArrayIndexOutOfBounds checks.
I would recommend to put a static array inside a class where that method is located and still call the method from outside code and just use the array from within the function. Yes, you will have some overhead for a funcall but I suppose you're not trying to gain like 0.001% of performance? Also JIT will probably simplify it. Most importantly your interface will be consistent and it will look like a normal function not like some hack. If you're trying to get some performance from a costly function by precalculation you can also consider memoization. The thing with hiding this array behind the funcall is that you can use any technique of caching or precalculation later without disturbing public interface.
E.g.
class A {
private final static int values[] = {0, 1, 2 ... };
public int myFun(int x){
return values[x];
}
}
for one you could just simplify your function (the /9/3*3 and the parens are very unnecessary. I know this is an example but just always look for ways of simplifying)
secondly if you function is simple enough, the "spedup" methods are not necessarily faster. Generally your lookup table method is not exactly scalable
third if you still want a lookup table method, just create an object that holds the values.
Related
Should I use a normal method that needs an object to call it or a static function method for an increment in the value of a data member of an object. Such as
public void incSize() {
this.size++;
}
or such as
public static void incSize(Number num1) {
num1.size++;
}
For something like this, where the logic and purpose of the function is intrinsically bound to a single object, use a member function instead of a static one. It means that all the operations you can perform on an object are grouped logically by the object you perform the operation on, which is easier to use.
In my opinion, and likely the opinions of many others, it's much easier to see what's going on with:
foo.incSize();
Compared to:
Foo.incSize(foo);
Static functions are good for describing computation that's relevant to a class, but not necessarily dependent on having an object of that class. For example, Integer.parseInt is static because the functionality of parsing to an integer is relevant to the integer class, but is still usable when you don't have an object of that class. Again, compare:
int x = Integer.parseInt("0");
To:
Integer x;
x.parseInt("0");
I'm a complete Java noob. I know that Java treats all parameters as pass by value and there are several other threads where people explain this.
For example, in C++ I can do:
void makeAThree(int &n)
{
n = 3;
}
int main()
{
int myInt = 4;
makeAThree(myInt);
cout << myInt;
}
Which will output 3. I know that in Java, all parameters are passed by value and thus you can not manipulate the parameter passed in. Is there a standard way to simulate pass by reference in Java? Is there no way to call a function that manipulates a variable passed in? It's tough for me to wrap my head around the idea of there being no way to do this.
The primary way you can simulate passing a reference is to pass a container that holds the value.
static void makeAThree(Reference<Integer> ref)
{
ref.set(3);
}
public static void main(String[] args)
{
Reference<Integer> myInt = new Reference<>(4);
makeAThree(myInt);
System.out.println(myInt.get());
}
Since in Java, it is references to objects that are passed by value (the object itself is never passed at all), setting ref to 3 in makeAThree changes the same object referred to by myInt in main().
Disclaimer: Reference isn't a class you can just use with out-of-the-box Java. I'm using it here as a placeholder for any other object type. Here's a very simple implementation:
public class Reference<T> {
private T referent;
public Reference(T initialValue) {
referent = initialValue;
}
public void set(T newVal) {
referent = newVal;
}
public T get() {
return referent;
}
}
Edit
That's not to say it's great practice to modify the arguments to your method. Often this would be considered a side-effect. Usually it is best practice to limit the outputs of your method to the return value and this (if the method is an instance method). Modifying an argument is a very "C" way of designing a method and doesn't map well to object-oriented programming.
You can use an array of size 1
Java pass everything by value, if it's an object then what would be passed is the reference value of the object. It's like,
void someMethod()
{
int value = 4;
changeInt(value);
System.out.printlin(value);
}
public void changeInt(int x)
{
x = x + 1;
}
above code will print 4, because it's passed by value
class SomeClass
{
int x;
}
void someMethod()
{
SomeClass value = new SomeClass();
value.x = 4;
changeCls(value);
System.out.printlin(value.x);
}
public void changeCls(SomeClass cls)
{
cls = new SomeClass();
cls.x = 5;
}
Above code will still print 4, because the object is passed by value and the reference to the object is passed here, even it's changed inside the method it won't reflect to the method 'someMethod'.
class SomeClass
{
int x;
}
void someMethod()
{
SomeClass value = new SomeClass();
value.x = 4;
changeCls(value);
System.out.printlin(value.x);
}
public void changeCls(SomeClass cls)
{
cls.x = cls.x + 1;
}
here also it passes the object by value, and this value will be the reference to the object. So when you change some field of this object it will reflect to the all the places where the object is referred. Hence it would print 5. So this can be the way you can use to do what you want. Encapsulate the value in an object and pass it to the method where you want to change it.
Java is pass-by-value that mean pass-by-copy. We cannot do arithmetic on a reference variable as in C++. In-short Java is not C/C++.
So as a workaround you can do this:
public static void main (String [] args) {
int myInt = 4;
myInt = makeAThree(myInt);
}
static int makeAThree(int n)
{
return n = 3;
}
P.S. Just made the method static so as to use it without class object. No other intention. ;)
I ran some of the various scenarios above.
Yes, if you wanted to change a value outside of the function without returning the same primitive, you'd have to pass it a single unit array of that primitive. HOWEVER, in Java, Array's are all internal objects. You please note that if you pass 'value' by name to the println() there is no compile error and it prints hashes because of the toString() native to the internal array class. You will note that those names change as they print (put it in a long loop and watch). Sadly, Java hasn't gotten the idea that we WOULD like a protected yet physically static address space available to us for certain reasons. It would hurt Java's security mechanisms though. The fact that we can't depend on known addresses means that it's harder to hack at that. Java performance is fantastic because we have fast processors. If you need faster or smaller, that's for other languages. I remember this from way back when in 1999 reading an article in Dobbs just about this argument. Since it's a web aware language meant to function online, this was a big design concession to security. Your PC in 1999 had 64mb to 256mb of RAM and ran around 800mhz
Today, your mobile device has 2 to 8 times that ram and is 200-700mhz faster and does WAY more ops per tick, and Java is the preferred language for Android, the dominant OS by unit sales (iOS still rocks, i gotta learn Objective C someday i guess, hate the syntax i've seen though).
If you passed int[] instead of int to this code you get 5 back from someMethod() calling it.
public void changeInt(int x)
{
x = x + 1;
}
public void changeInt(int[] x)
{
x[0] += 1;
}
This is a confusing selection from above. The code WOULD work if the author hadn't hidden the passed variable by declaring a local variable of the same name. OFCOURSE this isn't going to work, ignore the following example cited from above for clarity.
public void changeCls(SomeClass cls)
{
cls = new SomeClass();
cls.x = 5;
}
Above code will still print 4, because the passed object is HIDDEN FROM SCOPE by the local declaration. Also, this is inside a method, so I think even calling this and super wouldn't clarify it properly.
If it weren't hidden locally in the method, then it would have changed the value of the object passed externally.
To accomplish the changing of a primitive variable in a method there are 2 basic options :
1) If you want to change values on a primitive in a different method you can wrap the primitive in a "java bean" object, which will be essentially like a pointer.
Or
2) You can use an AtomicInteger/AtomicLong class which are used to concurrency, when many threads might need to modify a variable....so the variables has to have state that is consistent. Theses classes wrap primitives for you.
Warning : you are usually better off returning the new value, rather than setting/editting it internally in a method, from a maintainability standpoint ..
One quick way to achieving simulate passing by reference is to move the arguments to member variables of the enclosing class.
Although there are multiple ways to do it such as using a class or array wrapper or moving them to the function return type, the code may not turn out clean. If you are like me, the reason to ask such a question is that a piece of Java code has already been coded in a C++ way (which does not work) and a quick fix is needed. For example, in a recursion program such as depth-first-search, we may need to keep multiple variables in the C++ recursion function's argument list such as search path, flags whether the search should end. If you are in such a situation, the quickest fix is to make these argument variables into class member variables. Take care of the variable life cycle though and reset their values when necessary.
Java uses pass by value for everything.
As far as I understand you are not really sure if you can modify a variable passed in.
When you pass an object to a method, and if you use that object within that method, you are actually modifying that object. However you are modifying that object on a copy of it which still points to the same object. So actually when you pass an object to a method, you can modify it.
Once again, everything in java is pass by value.period.
The Situation is that I have to use Function pointers for so many functions in Java (so I did it this way) and saved each anonymous class to a static variable of the Interface, so that I could use them directly.
/** The Constant HARDLIM. */
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(DoubleMatrix netSum, double theta) {
return netSum.gt(theta);
}
public String getFuncName() {
return "HARDLIM";
}
};
But the problem is that sometimes I don't need to provide the Theta so if I remove it the polymorphism won't work, (2 Functions out of 10 don't need theta) so I had to put it (Function declaration conventions now ugly) so I thought of passing the whole Object which actually contains both netsum and theta.
But I'm starting to worry, cause it's also going to ruin what this function really is for. So at last I suggested I put these function separately (non anonymous) and then make anonymous functions use them but the argument would be the object. Like the following:
/** The Constant HARDLIM. */
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(MyObject obj) {
return MyObjectUtilFun.hardlim(obj.getNetsum,obj.getTheta);
}
public String getFuncName() {
return "HARDLIM";
}
};
So Am I taking the right steps ? or I'm messing around, Please guide me!
Do you really need the instance to be public static final? If you can instantiate the instance wherever you have a reference to theta, then your anonymous class can use that theta reference. For example:
final double theta = 123d;
class TransferePatternable {
public String transfere(String whatever) {
return whatever + theta;
}
}
TransferePatternable myInstance = new TransferePatternable();
myInstance.transfere("arg");
Alternatively you can specify the input as a generic type such that your MyObject need not be a superset of all possible inputs, but rather can differ by TransferePatternable type. Obviously the drawback here is that you need to know what type you're calling in order to provide the right input, but you sort of need to know this anyway if you don't want to provide theta in some situations.
Finally, another common solution to this problem is to replace ALL method parameters with just one Map. Then, you can pass in whatever you want! This has lots of obvious drawbacks, but lots of APIs do exactly this, and generally you'll see them refer to the map as the "context". Here are a few examples:
javax.servlet .ServletRequests store parameters in a Map
AOP has the javax.interceptor.InvocationContext class
Spring's IoC container basically is a big Map of named javabeans
The JSP Expression Language allows you to refer to Implicit Objects that basically are stored in several Maps
I myself have used this Map solution when implementing an Excel-like formula language in java years ago. Such a formula can be parsed into functions and variables, and when executing the function we provided a Map containing the variables keyed by variable name. Obviously you still need to know something about what you're invoking, and in fact we always did know enough about the formula that providing the right inputs in a Map was easy. But again I have to caution you: this sort of code is fairly hard to implement and maintain. Unless you anticipate growing a large set of functions over time, don't go down this route. It's not OO-friendly, and it should be a last resort.
If MyObject is a generally used interface or class and TransferePatternable is not expected to work with anything else, your second idea is best. It opens up the possibilities of a TransferePatternable being able to work with more than just netSum and theta and gets rid of the unneeded theta. My guess is that this is what you want to do, even if it means expanding the capabilities and scope and importance of the MyObject class/interface.
But you are restricting a TransferePatternable to working with a MyObject instance. The unused theta is a problem, but it's a small price to pay for the power of polymorphism (and its a lot simpler and neater than most other solutions). If the MyObject solution doesn't look perfect to you, stick with the unused theta. My guess is a good idea will come along sooner or later, with no harm done if it doesn't.
Is there any reason you can't have an overloaded "transfere" function in the HARDLIM?
/** The Constant HARDLIM. */
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(DoubleMatrix netSum, double theta) {
return netSum.gt(theta);
}
public DoubleMatrix transfere(DoubleMatrix netSum) {
return netSum.whateverYouNeedToDoWithoutTheta();
}
public String getFuncName() {
return "HARDLIM";
}
};
At the end I used The second choice but with some notes in mind:
To always have functions (i.e Hardlim) defined independently in utility classes.
To state in Javadocs what this variable really is and the utility function being used.
I also found the price of confusing users with unnecessary arguments to be high cause the application is already complex no need to be more complicated.
public static final TransferePatternable HARDLIM =
new TransferePatternable() {
public DoubleMatrix transfere(MyObject obj) {
return MyObjectUtilFun.hardlim(obj.getNetsum,obj.getTheta);
}
public String getFuncName() {
return "HARDLIM";
}
};
Recently I refactored the code of a 3rd party hash function from C++ to C. The process was relatively painless, with only a few changes of note. Now I want to write the same function in Java and I came upon a slight issue.
In the C/C++ code there is a C preprocessor macro that takes a few integer variables names as arguments and performs a bunch of bitwise operations with their contents and a few constants. That macro is used in several different places, therefore its presence avoids a fair bit of code duplication.
In Java, however, there is no equivalent for the C preprocessor. There is also no way to affect any basic type passed as an argument to a method - even autoboxing produces immutable objects. Coupled with the fact that Java methods return a single value, I can't seem to find a simple way to rewrite the macro.
Avenues that I considered:
Expand the macro by hand everywhere: It would work, but the code duplication could make things interesting in the long run.
Write a method that returns an array: This would also work, but it would repeatedly result into code like this:
long tmp[] = bitops(k, l, m, x, y, z);
k = tmp[0];
l = tmp[1];
m = tmp[2];
x = tmp[3];
y = tmp[4];
z = tmp[5];
Write a method that takes an array as an argument: This would mean that all variable names would be reduced to array element references - it would be rather hard to keep track of which index corresponds to which variable.
Create a separate class e.g. State with public fields of the appropriate type and use that as an argument to a method: This is my current solution. It allows the method to alter the variables, while still keeping their names. It has the disadvantage, however, that the State class will get more and more complex, as more macros and variables are added, in order to avoid copying values back and forth among different State objects.
How would you rewrite such a C macro in Java? Is there a more appropriate way to deal with this, using the facilities provided by the standard Java 6 Development Kit (i.e. without 3rd party libraries or a separate preprocessor)?
Option 3, create you own MutableInteger wrapper class.
struct MutableInteger{
public MutableInteger(int v) { this.value = value;}
public int value;
}
public void swap3( MutableInteger k, MutableInteger l, MutableInteger m) {
int t = m.value;
m.value = l.value
l.value=k.value;
k.value=t;
}
Create a separate class e.g. State
with public fields of the appropriate
type and use that as an argument to a
method
This, but as an intermediate step. Then continue refactoring - ideally class State should have private fields. Replace the macros with methods to update this state. Then replace all the rest of your code with methods that update the state, until eventually your program looks like:
System.out.println(State(System.in).hexDigest());
Finally, rename State to SHA1 or whatever ;-)
How can I pass a primitive type by reference in java? For instance, how do I make an int passed to a method modifiable?
There isn't a way to pass a primitive directly by reference in Java.
A workaround is to instead pass a reference to an instance of a wrapper class, which then contains the primitive as a member field. Such a wrapper class could be extremely simple to write for yourself:
public class IntRef { public int value; }
But how about some pre-built wrapper classes, so we don't have to write our own? OK:
The Apache commons-lang Mutable* classes:
Advantages: Good performance for single threaded use. Completeness.
Disadvantages: Introduces a third-party library dependency. No built-in concurrency controls.
Representative classes: MutableBoolean, MutableByte, MutableDouble, MutableFloat, MutableInt, MutableLong, MutableObject, MutableShort.
The java.util.concurrent.atomic Atomic* classes:
Advantages: Part of the standard Java (1.5+) API. Built-in concurrency controls.
Disadvantages: Small performance hit when used in a single-threaded setting. Missing direct support for some datatypes, e.g. there is no AtomicShort.
Representative classes: AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference.
Note: As user ColinD shows in his answer, AtomicReference can be used to approximate some of the missing classes, e.g. AtomicShort.
Length 1 primitive array
OscarRyz's answer demonstrates using a length 1 array to "wrap" a primitive value.
Advantages: Quick to write. Performant. No 3rd party library necessary.
Disadvantages: A little dirty. No built-in concurrency controls. Results in code that does not (clearly) self-document: is the array in the method signature there so I can pass multiple values? Or is it here as scaffolding for pass-by-reference emulation?
Also see
The answers to StackOverflow question "Mutable boolean field in Java".
My Opinion
In Java, you should strive to use the above approaches sparingly or not at all. In C it is common to use a function's return value to relay a status code (SUCCESS/FAILURE), while a function's actual output is relayed via one or more out-parameters. In Java, it is best to use Exceptions instead of return codes. This frees up method return values to be used for carrying the actual method output -- a design pattern which most Java programmers find to be more natural than out-parameters.
Nothing in java is passed by reference. It's all passed by value.
Edit: Both primitives and object types are passed by value. You can never alter the passed value/reference and expect the originating value/reference to change. Example:
String a;
int b;
doSomething(a, b);
...
public void doSomething(String myA, int myB) {
// whatever I do to "myA" and "myB" here will never ever ever change
// the "a" and "b"
}
The only way to get around this hurdle, regardless of it being a primitive or reference, is to pass a container object, or use the return value.
With a holder:
private class MyStringHolder {
String a;
MyStringHolder(String a) {
this.a = a;
}
}
MyStringHolder holdA = new MyStringHolder("something");
public void doSomething(MyStringHolder holder) {
// alter holder.a here and it changes.
}
With return value
int b = 42;
b = doSomething(b);
public int doSomething(int b) {
return b + 1;
}
Pass an AtomicInteger, AtomicBoolean, etc. instead. There isn't one for every primitive type, but you can use, say, an AtomicReference<Short> if necessary too.
Do note: there should very rarely be a need to do something like this in Java. When you want to do it, I'd recommend rethinking what you're trying to do and seeing if you can't do it some other way (using a method that returns an int, say... what exactly the best thing to do is will vary from situation to situation).
That's not possible in Java, as an alternative you can wrap it in a single element array.
void demo() {
int [] a = { 0 };
increment ( a )
}
void increment( int [] v ) {
v[0]++;
}
But there are always better options.
You can't. But you can return an integer which is a modified value
int i = 0;
i = doSomething(i);
If you are passing in more than one you may wish to create a Data Transfer Object (a class specifically to contain a set of variables which can be passed to classes).
Pass an object that has that value as a field.
That's not possible in Java
One option is to use classes like java.lang.Integer, then you're not passing a primitive at all.
On the other hand, you can just use code like:
int a = 5;
a = func(a);
and have func return the modified value.