Saving List of Strings in Java - java

am having problem in Saving some data in my Java code.
I have like three different methods which do some respective tasks. Am calling these methods using Hessian from Php client. And am not calling this three methods at a time. Each method will create some arrays(contains strings, int, float), and some time i have to use those arrays which was created my previous methods call in this present method.
Is there any way i can save that Arrays(not in database), may be a List or Array which will not flush the memory unless i say soo..
Example
public class top{
Method1(){
String[] stringA = {some string data} ;
}
Method2(){
for(string data : stringA){
I use array of stringA from method1 without calling the whole method1. I need that string value to be save untill i flush it out.
}
}
}
This is not a complete code.. not even a code. Am just trying to explain the issue.
Any help please.
Thanks.

How about defining the stringA as a instance variable instead of a local variable ?

You could set up stringA as a local variable to your class.
public class SomeClass {
private String[] stringA;
public void method1(){
stingA = "something";
}
public void method2(){
for(string data : stringA){
I use array of stringA from method1 which out calling the whole method. I need that string value to be save untill i flush it out.
}
}
You could also use a ArrayList, instead of an array for your string. This will allow you to dynamically grow your list. If you want to "flush" it, you could just call the clear() method
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("string1");
myArr.add("string2");
//clear the ArrayList
myArr.clear()

If you want to remember values between method calls, it should be a instance (class
level) variable. If yours is a web application, you can use session variables.
[Your code is not complete, actually its not even there. Posting complete code helps someone trying to answer to understand the problem correctly.]

I don't know anything about hessian, but it looks like that the component that handles the call is stateless.
I agree with Nivas' answer in this case.
However, should you need extra functionality (search, etc) with the storage and have some hardware resource to spend you can also use something like HSQLDB which have in-memory DB storage (very fast).

Related

Java ArrayList issue

I need some help with a line of code in a program that I am writing. I feel like it's going to be some stupid mistake but I just can't seem to figure out what it is...
ArrayList<Integer> knockSequence; //Default knockSequence
ArrayList<ArrayList<Integer>> customSequences; //used to store custom sequences for client after first connection
ArrayList<ServerClient> connectedClients; //List of connected clients
//...
public void giveNewSequence(ArrayList<Integer> newSequence, ServerClient client) //client MUST be in connectedClients in order for this to work
{
customSequences.get(connectedClients.indexOf(client)) = newSequence;
}
Why won't the line "customSequences.get(......." work? The error I'm getting is saying that it is looking for a variable but a value is being found. Any feedback is appreciated
Why won't the line "customSequences.get(......." work?
You're trying to assign a value to the result of a method call. That's what doesn't work. You can only use the assignment operator with a variable.
I suspect you want:
customSequences.set(connectedClients.indexOf(client), newSequence);
You should also consider using a single collection with a composite type which contains the knock, custom sequence and connected client, rather than managing three separate collections where the values are related by index (which is what I suspect you've got here). You might want to use a map as well, rather than a list.

Passing a parameter versus returning it from function

As it might be clear from the title which approach should we prefer?
Intention is to pass a few method parameters and get something as output. We can pass another parameter and method will update it and method need not to return anything now, method will just update output variable and it will be reflected to the caller.
I am just trying to frame the question through this example.
List<String> result = new ArrayList<String>();
for (int i = 0; i < SOME_NUMBER_N; i++) {
fun(SOME_COLLECTION.get(i), result);
}
// in some other class
public void fun(String s, List<String> result) {
// populates result
}
versus
List<String> result = new ArrayList<String>();
for (int i = 0; i < SOME_NUMBER_N; i++) {
List<String> subResult = fun(SOME_COLLECTION.get(i));
// merges subResult into result
mergeLists(result, subResult);
}
// in some other class
public List<String> fun(String s) {
List<String> res = new ArrayList<String>();
// some processing to populate res
return res;
}
I understand that one passes the reference and another doesn't.
Which one should we prefer (in different situations) and why?
Update: Consider it only for mutable objects.
Returning a value from the function is generally a cleaner way of writing code. Passing a value and modifying it is more C/C++ style due to the nature of creating and destroying pointers.
Developers generally don't expect that their values will be modified by passing it through a function, unless the function explicitly states it modifies the value (and we often skim documentation anyway).
There are exceptions though.
Consider the example of Collections.sort, which does actually do an in place sort of a list. Imagine a list of 1 million items and you are sorting that. Maybe you don't want to create a second list that has another 1 million entries (even though these entries are pointing back to the original).
It is also good practice to favor having immutable objects. Immutable objects cause far fewer problems in most aspects of development (such as threading). So by returning a new object, you are not forcing the parameter to be mutable.
The important part is to be clear about your intentions in the methods. My recommendation is to avoid modifying the parameter when possible since it not the most typical behavior in Java.
You should return it. The second example you provided is the way to go.
First of all, its more clear. When other people read your code, there's no gotcha that they might not notice that the parameter is being modified as output. You can try to name the variables, but when it comes to code readability, its preferable.
The BIG reason why you should return it rather than pass it, is with immutable objects.
Your example, the List, is mutable, so it works okay.
But if you were to try to use a String that way, it would not work.
As strings are immutable, if you pass a string in as a parameter, and then the function were to say:
public void fun(String result){
result = "new string";
}
The value of result that you passed in would not be altered. Instead, the local scope variable 'result' now points to a new string inside of fun, but the result in your calling method still points to the original string.
If you called:
String test = "test";
fun(test);
System.out.println(test);
It will print: "test", not "new string"!
So definitely, it is superior to return. :)
This is more about best practices and your own method to program. I would say if you know this is going to be a one value return type function like:
function IsThisNumberAPrimeNumber{ }
Then you know that this is only going to ever return a boolean. I usually use functions as helper programs and not as large sub procedures. I also apply naming conventions that help dictate what I expect the sub\function will return.
Examples:
GetUserDetailsRecords
GetUsersEmailAddress
IsEmailRegistered
If you look at those 3 names, you can tell the first is going to give you some list or class of multiple user detail records, the second will give you a string value of a email and the third will likely give you a boolean value. If you change the name, you change the meaning, so I would say consider this in addition.
The reason I don't think we understand is that those are two totally different types of actions. Passing a variable to a function is a means of giving a function data. Returning it from the function is a way of passing data out of a function.
If you mean the difference between these two actions:
public void doStuff(int change) {
change = change * 2;
}
and
public void doStuff() {
int change = changeStorage.acquireChange();
change = change * 2;
}
Then the second is generally cleaner, however there are several reasons (security, function visibilty, etc) that can prevent you from passing data this way.
It's also preferable because it makes reusing code easier, as well as making it more modular.
according to guys recommendation and java code convention and also syntax limitation this is a bad idea and makes code harder to understand
BUT you can do it by implementing a reference holder class
public class ReferenceHolder<T>{
public T value;
}
and pass an object of ReferenceHolder into method parameter to be filled or modified by method.
on the other side that method must assign its return into Reference value instead of returning it.
here is the code for getting result of an average method by a ReferenceHolder instead of function return.
public class ReferenceHolderTest {
public static void main(String[] args) {
ReferenceHolder<Double> out = new ReferenceHolder<>();
average(new int[]{1,2,3,4,5,6,7,8},out);
System.out.println(out.value);
}
public static void average(int[] x, ReferenceHolder<Double> out ) {
int sum=0;
for (int a : x) {
sum+=a;
}
out.value=sum/(double)x.length;
}
}
Returning it will keep your code cleaner and cause less coupling between methods/classes.
It is generally preferable to return it.
Specially from a unit testing standpoint. If you are unit testing it
is easier to assert a returned value from a method than verifying if
your object was modified or interacted correctly. (Using
ArgumentCaptor or ArgumentMatcher to assert interactions isn't as
straight forward as a simple return assertion).
Increased code readability. If I see a method that takes 5 object parameters I
might have no immediate way of knowing you plan on modifying one of
those references for future use downstream. Instead if you are returning an
object, I can easily see you ultimately care about the result of that
method's computation.

Usage of sun.misc.SharedSecrets

I found this little gem in our codebase at work recently. I have to confess that I have absolutely no idea why this enum was written in this way (names changed to protect the innocent):
package foo.bar;
import sun.misc.SharedSecrets;
import foo.baz.HasAGetValuesMethod;
public enum MysteryEnum implements HasAGetValuesMethod {
THINGY, BOB;
#Override
public MysteryEnum[] getValues() {
return SharedSecrets.getJavaLangAccess().getEnumConstantsShared(MysteryEnum .class);
}
}
In the getValues() method instead of simply calling MysteryEnum.values() it's using something called sun.misc.SharedSecret to get a handle to something called sun.misc.JavaLangAccess, then using that to get an array of all the enum values. The Javadoc on that class tells you what the method does, but I can't find much on why you would want to call it.
The developer that wrote this is no longer around, so I can't ask him. I'm going to ask my team anyway, but I have a feeling that the answer will be: "Don't know why it does that, but better not change it". For the moment, I'm assuming that this is either an odd case of someone not knowing that the values() method exists, or that my ignorance of the sun.misc libraries is causing me to miss something obvious to others. Any idea's why this code was written this way?
The method returns the same array without reflection or copying/cloning the underlying array. This improves performance, but is not a good idea to exposes a mutable array.
for (int i = 0; i < 3; i++)
System.out.println(SharedSecrets.getJavaLangAccess().getEnumConstantsShared(AccessMode.class));
AccessMode[] ams = SharedSecrets.getJavaLangAccess().getEnumConstantsShared(AccessMode.class);
ams[1] = ams[2]; // don't do this !!
System.out.println(EnumSet.allOf(AccessMode.class));
prints
[Ljava.nio.file.AccessMode;#330cdec1
[Ljava.nio.file.AccessMode;#330cdec1
[Ljava.nio.file.AccessMode;#330cdec1
[READ, EXECUTE, EXECUTE]
Instead of using this method, what I do is use my own cached copy
// cannot be modified.
private static final AccessMode[] ACCESS_MODES = AccessMode.values();
Basically SharedSecret:
A repository of "shared secrets", which are a mechanism for
calling implementation-private methods in another package without
using reflection.
The code returns the enum constants by reading the class and returning the constants back (without needing to do reflection calls). This is dynamic in a way that if a new enum constant is added to the enum, the getValues() method will return the added enums (no need to change code all over the show).
The documentation says:
Returns the elements of an enum class or null if the Class object does
not represent an enum type; the result is uncloned, cached, and shared
by all callers.
So, unless the point was to provide a shared array, so that anyone could break everything by setting one of its elements to null, or sorting it, or whatever (which could have been done by caching the result of the values() method), my guess is also that this line is there due to the incompetence of the previous developer.
I would write a unit test, then replace it with a call to values() and check that the unit test still passes.
Just for information:
I was looking into the implementation of EnumMap and found the same code snippet where all enum values are fetched from the class name.
/**
* Returns all of the values comprising K.
* The result is uncloned, cached, and shared by all callers.
*/
private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
return SharedSecrets.getJavaLangAccess()
.getEnumConstantsShared(keyType);
}

Should Java method arguments be used to return multiple values?

Since arguments sent to a method in Java point to the original data structures in the caller method, did its designers intend for them to used for returning multiple values, as is the norm in other languages like C ?
Or is this a hazardous misuse of Java's general property that variables are pointers ?
A long time ago I had a conversation with Ken Arnold (one time member of the Java team), this would have been at the first Java One conference probably, so 1996. He said that they were thinking of adding multiple return values so you could write something like:
x, y = foo();
The recommended way of doing it back then, and now, is to make a class that has multiple data members and return that instead.
Based on that, and other comments made by people who worked on Java, I would say the intent is/was that you return an instance of a class rather than modify the arguments that were passed in.
This is common practice (as is the desire by C programmers to modify the arguments... eventually they see the Java way of doing it usually. Just think of it as returning a struct. :-)
(Edit based on the following comment)
I am reading a file and generating two
arrays, of type String and int from
it, picking one element for both from
each line. I want to return both of
them to any function which calls it
which a file to split this way.
I think, if I am understanding you correctly, tht I would probably do soemthing like this:
// could go with the Pair idea from another post, but I personally don't like that way
class Line
{
// would use appropriate names
private final int intVal;
private final String stringVal;
public Line(final int iVal, final String sVal)
{
intVal = iVal;
stringVal = sVal;
}
public int getIntVal()
{
return (intVal);
}
public String getStringVal()
{
return (stringVal);
}
// equals/hashCode/etc... as appropriate
}
and then have your method like this:
public void foo(final File file, final List<Line> lines)
{
// add to the List.
}
and then call it like this:
{
final List<Line> lines;
lines = new ArrayList<Line>();
foo(file, lines);
}
In my opinion, if we're talking about a public method, you should create a separate class representing a return value. When you have a separate class:
it serves as an abstraction (i.e. a Point class instead of array of two longs)
each field has a name
can be made immutable
makes evolution of API much easier (i.e. what about returning 3 instead of 2 values, changing type of some field etc.)
I would always opt for returning a new instance, instead of actually modifying a value passed in. It seems much clearer to me and favors immutability.
On the other hand, if it is an internal method, I guess any of the following might be used:
an array (new Object[] { "str", longValue })
a list (Arrays.asList(...) returns immutable list)
pair/tuple class, such as this
static inner class, with public fields
Still, I would prefer the last option, equipped with a suitable constructor. That is especially true if you find yourself returning the same tuple from more than one place.
I do wish there was a Pair<E,F> class in JDK, mostly for this reason. There is Map<K,V>.Entry, but creating an instance was always a big pain.
Now I use com.google.common.collect.Maps.immutableEntry when I need a Pair
See this RFE launched back in 1999:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4222792
I don't think the intention was to ever allow it in the Java language, if you need to return multiple values you need to encapsulate them in an object.
Using languages like Scala however you can return tuples, see:
http://www.artima.com/scalazine/articles/steps.html
You can also use Generics in Java to return a pair of objects, but that's about it AFAIK.
EDIT: Tuples
Just to add some more on this. I've previously implemented a Pair in projects because of the lack within the JDK. Link to my implementation is here:
http://pbin.oogly.co.uk/listings/viewlistingdetail/5003504425055b47d857490ff73ab9
Note, there isn't a hashcode or equals on this, which should probably be added.
I also came across this whilst doing some research into this questions which provides tuple functionality:
http://javatuple.com/
It allows you to create Pair including other types of tuples.
You cannot truly return multiple values, but you can pass objects into a method and have the method mutate those values. That is perfectly legal. Note that you cannot pass an object in and have the object itself become a different object. That is:
private void myFunc(Object a) {
a = new Object();
}
will result in temporarily and locally changing the value of a, but this will not change the value of the caller, for example, from:
Object test = new Object();
myFunc(test);
After myFunc returns, you will have the old Object and not the new one.
Legal (and often discouraged) is something like this:
private void changeDate(final Date date) {
date.setTime(1234567890L);
}
I picked Date for a reason. This is a class that people widely agree should never have been mutable. The the method above will change the internal value of any Date object that you pass to it. This kind of code is legal when it is very clear that the method will mutate or configure or modify what is being passed in.
NOTE: Generally, it's said that a method should do one these things:
Return void and mutate its incoming objects (like Collections.sort()), or
Return some computation and don't mutate incoming objects at all (like Collections.min()), or
Return a "view" of the incoming object but do not modify the incoming object (like Collections.checkedList() or Collections.singleton())
Mutate one incoming object and return it (Collections doesn't have an example, but StringBuilder.append() is a good example).
Methods that mutate incoming objects and return a separate return value are often doing too many things.
There are certainly methods that modify an object passed in as a parameter (see java.io.Reader.read(byte[] buffer) as an example, but I have not seen parameters used as an alternative for a return value, especially with multiple parameters. It may technically work, but it is nonstandard.
It's not generally considered terribly good practice, but there are very occasional cases in the JDK where this is done. Look at the 'biasRet' parameter of View.getNextVisualPositionFrom() and related methods, for example: it's actually a one-dimensional array that gets filled with an "extra return value".
So why do this? Well, just to save you having to create an extra class definition for the "occasional extra return value". It's messy, inelegant, bad design, non-object-oriented, blah blah. And we've all done it from time to time...
Generally what Eddie said, but I'd add one more:
Mutate one of the incoming objects, and return a status code. This should generally only be used for arguments that are explicitly buffers, like Reader.read(char[] cbuf).
I had a Result object that cascades through a series of validating void methods as a method parameter. Each of these validating void methods would mutate the result parameter object to add the result of the validation.
But this is impossible to test because now I cannot stub the void method to return a stub value for the validation in the Result object.
So, from a testing perspective it appears that one should favor returning a object instead of mutating a method parameter.

Can you get the previous value of a variable in Java?

Say way have a variable (let's say String Str) and the value of Str starts of as " " then as some code is running it is set to "test" then somewhere else in the code it is changed again to say "tester". Now in the program I want to find out what the previous value of Str was. Is this possible in Java?
So I am saying that the variable gets changed twice, and you want to find out what Str was before it got changed for the second time. So in the example above the latest value of Str would be "tester" but I wanted to find out what Str was before this (assuming you had no idea what it was before it was changed to tester) in this case I would want to be able to find out that Str was "test".
Is it at all possible to do this in Java?
No, it's not possible, you have to save the previous value before you change it to do what you're asking for.
Not as a native part of the language, no. You could write a setter that saved the current (previous?) value when the String changes, though.
private String str;
private String prev;
setStr(String s)
{
prev = str;
str = s;
}
Then just write a separate getter for prev.
Of course, this solution relies on you always using the setter to change the value of str.
Also, as deworde points out, if your program doesn't need this information, then you shouldn't modify your program to save it. If you need the information for debugging purposes you can just set a watch in your IDE's debugger.
Simple answer, no.
However, you could use:
AOP
An AOP framwork, such as AspectJ could intercept assignments to a variable.
See AspectJ pointcut reference
JavaBeans Property Change Support
You could use standard JavaBean setters, getters to encapsulate your field. Then you can register listeners on a bean to listen out for property changes, and even veto that change.
See JavaBean Spec for more information.
Example listener:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class MyBeanListener implements PropertyChangeListener,
VetoableChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.printf("Notifed of property changed event: %s => %s%n", evt
.getOldValue(), evt.getNewValue());
}
#Override
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
System.out.printf("Notified of vetoable change event: %s => %s%n", evt
.getOldValue(), evt.getNewValue());
}
}
If you really have a strong need for this you could use the following code:
public class Main
{
public static void main(final String[] argv)
{
SavedValue<Integer> i;
i = new SavedValue<Integer>();
i.set(7);
System.out.println(i.get());
System.out.println(i.getOld());
}
}
class SavedValue<T>
{
private T oldValue;
private T value;
void set(final T val)
{
oldValue = value;
value = val;
}
T get()
{
return (value);
}
T getOld()
{
return (oldValue);
}
}
Perhaps you could explain why you want the old value? I am sure we can give you much better answers if we knew why yoiu wanted it.
You already got the two simple answers:
No, Java itself doesn't allow that
You can use setters and implement a mechanism to keep the old value(s)
But there is a third one which I haven't seen so far:
It should be possible to write an Aspect in AspectJ that triggers on the assignment. So it would have a similar effect as a setter, without the actual setter. If you are working with code that you don't want to or cannot change this might be an option.
Note that while AspectJ isn't Java the result is normal byte code, so it should be compatible with most environments.
Of course instead of using AspectJ you could do this with CGLIB.
It looks like you're using this for debugging, am I right?
Visual Studio, or any decent debugger should allow you to print a trace of the value every time it's set just by putting a "tracepoint" before and after all the calls that set the value.
You just alter the properties of a normal breakpoint to print a statement rather than halt execution.
In VS2005 this is done by:
Bringing up the breakpoint window
Right-clicking on the breakpoint
Selecting the option "When Hit...".
Selecting "Print a Message" and entering a message
Making sure that "Continue Execution" is still selected.
This normally slows the program down significantly while debugging, so it's of little use for time-dependent debugging; but it's still allowed me to follow a variable's states (ABCDFEGH...)
Of course, if you do want to halt execution, just dump a normal breakpoint in.
You may try to use a stack data structure. It will keep all previous values in the right order. You may implement your own or use the java Collections one:
Deque<Integer> stack = new ArrayDeque<Integer>();
Each time you set the variable, put it in the stack (either through setter or AOP as mentioned in the other answers).
That way, you will be able to access al previous values.
Indeed, this is not possible. You'd have to create your own String class that had some sort of memory to achieve this.
In addition to what Stefan said, I would recommend a List structure of some kind containing all the historical values.
When you want to change the value, just add a new value to the end of the list. When you want to get the current value, just look at the last value. If you want to see previous values, start from the end of the list.
If you could find the previous state of the program, there would never be any garbage to collect and the program would very quickly run out of memory.
For specific variables, you could use, say, a LIFO stack. Instead of an assignment you would push to the stack. Instead of reading the variable, you would peek. The contents of the stack can be examined to find historical values.
Another approach would be to use instrumentation. This allows you to, with sufficient skill and patience, rewrite byte code to do what ever you want.
Perhaps you want to stand back a bit and look at what you are actually trying to achieve.
I don't know the reasons for wanting to do this, but I'm guessing it's debugging of some kind.
If you're using eclipse, you can set breakpoints that trigger when a variable changes. That might achieve what I assume you're trying to get to.
This is in fact possible using something called a Historical Debugger, and it is accomplished by instrumenting the bytecode so that any assignment to the variable is recorded.
Gooogle Bil Lewis Historical Debugger for one example. Note that most of this software is in what you'd call an 'initial beta' phase.
Have you heard about Jive? It allows backward stepping in debug so this is partially answer to your question Read here: http://www.cse.buffalo.edu/jive/
Yes!! When you change the value, the value is changed only for the particular object. See the ex:
class Test{
int a=100; //original value
Test(int b){
this.a=b;
}
Test(){
}
void print(){
System.out.println(a);
}
public static void main(String args[]){
Test t=new Test(9);
Test t2=new Test();
t.print(); //output: 9
t2.print(); //output: 100
}
}

Categories