Creating Variables at Runtime in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In my code I have a pretty big loop and I need to create a new variable at the end of each iteration (integers). Is this possible? I read about a ScriptEngineManager class, but I'm not sure if this will be able to help. I suppose I could create a bunch of integers equal to 0, but I'm not exactly sure how many times I will need to create a new variable (it depends on the conditions of the loop). Hopefully this makes sense.

Use an array. In Javascript, place var results = [] before your loop and append results using results.push(value). In Java, you'll want to use an ArrayList. (Those are very different languages, by the way.)

Hopefully this makes sense.
Unfortunately, it doesn't.
In Java it makes no sense to create variables on the fly. It is extremely difficult to do, and once you have done it they are extremely difficult to use. (By contrast, it is easy to do in Javascript ...)
However, this just means that you need to do what you are trying to in a different way. For instance, the following does a computation in a loop and then saves the results in an (existing) ArrayList variable:
List<Integer> results = ArrayList<Integer>();
while (...) {
// Do computation ...
int result = ...
results.add(result);
}
// Now we have all of the results in 'results'
Or, if you want to bind each of the results to a distinct name, you could do something like this:
Map<String, Integer> results = HashMap<String, Integer>();
while (...) {
// Do computation ...
String name = ...
int result = ...
results.put(name, result);
}

Following is the way that i have implemented and helped me to fix my solution easily without much hurdles.
// Creating the array List
List accountList = new ArrayList();
for(int k=0;k < counter;k++){
accountList.add(k, (String)flowCtx.getValueAt("transitId"+m));
}
Iterating the loop and adding the objects into the arraylist with the index.
//Retrieving the object at run time with the help of the index
String a = accountList.get(i));

No, It is not possible to declare variables in java at runtime. But java provides java.util.map, which can be used like in the example below. We can assume that the key is the variable name.
Map<String, Object> declareVariableRuntime= new HashMap<String, Object>(); declareVariableRuntime.put("variableName", new Object());

Related

Passing a reference through multiple methods, what aproach is better [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a HashMap that i need to send to 2 methos, each method might add entries to it, I return the HashMap afterwards. What is the more clean approach to this:
public HashMap<String, Boolean> getDataMap() {
HashMap<String, Boolean> resultMap = new HashMap<>();
gatherData1(resultMap);
gatherData2(resultMap);
return resultMap;
}
or
public HashMap<String, Boolean> getDataMap() {
HashMap<String, Boolean> resultMap = new HashMap<>();
resultMap = gatherData1(resultMap);
resultMap = gatherData2(resultMap);
return resultMap;
}
What approach is cleaner, in the second example it is more obvious that the 2 methods are there for operating on the input and returning a result so it is more readable but also maybe its not so usefull or even confusing for some. Im just interested in a proper way of doing things especially since this can get a lot more complex and as a result a lot harder to read and understand by other people
There is a major difference between the two snippets. The second one can return a new Map, that may or may not contain the data that was originally in the resultMap.
The first one can only mutate the input parameter, and it is a topic open for discussion wether or not methods are allowed to modify the input. Imho they should not, they should operate on the input and return output, end of story.
Therefore I would recommend / prefer the second snippet including modifying the gatherData implementation to not mutate the passed map but instead return a new one. You may even not pass resultMap in at all but instead just return a completely new map and make the merging / combining of the resultMap and the the return value of gatherData part of the getDataMap implementation. That should be the implementation if gatherData does not actually need the Map for some internal logic.
If this is just for config purposes and the gatherData methods are very simple, do not have a lot of logic or not much else happens to the resultMap then it may be fine to modify the input parameter.
If the method does not copy the map, but only adds entries (or removes or updates entries), then there is simply no need to return the map, as the reference to the map is the same across the caller and callee methods. It's not a matter of readability but more of avoiding redundant reassignment. If the method otherwise creates a new copy, then you'd have the return new map.

ArrayList<String> objects point to null. Why? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a piece of code that takes in an ArrayList<String> object and eventually takes that object and adds it to a HashMap object as the key. When I print the hashmap, the key's are all null while the values are correct.
I already know I can fix the code by passing in a copy of the ArrayList<String> object and that fixes my issue (i.e. buildHash(new ArrayList<String>(key)). But why does it point to null otherwise?
HashMap<ArrayList<String>, ArrayList<String>> hash = new HashMap<>();
ArrayList<String> key = new ArrayList<String>();
for (int i = 0; i <= 9999999; i++) {
key.add(//different strings depending on the iteration);
if ( !hash.contains(key) ) {
buildHash(key);
}
key.clear();
}
private void buildHash(ArrayList<String> key) {
ArrayList<String> follows = new ArrayList<String>();
for (int index = 0; index <= 9999999; index++) {
// add stuff to follows...
}
hash.put(key, follows);
}
I thought that the value of the key would be added to the hash, and the hash's keys would point to the value it was before it was cleared by key.clear(). That way I could reuse key over and over without creating another object in memory.
I'm new to Java (and coding) so I'm probably naive, but I thought I could save memory by utilizing the mutability of ArrayLists as opposed to Lists as the number of operations and key's generated for this project are well into the millions, if not more. Is there no avoiding that? And if not, is there any other optimization I could do?
As documented, ArrayList::clear removes all elements from the list. So you are wiping out the content.
utilizing the mutability of ArrayLists
Exactly what you do not want in a key. An object used as a key in a map should never be modifiable, not in a way that affects the outcome of the hash value calculation or affects the outcome of the equals method. Would you expect to find someone in a phone book after they changed their name?
It hard for me to imagine where you would ever want to use a list as a key in a map.
As for trying to “save memory”… don’t. The last thing a new programmer should worry about is conserving RAM. Write simple code, easy to read, easy to edit. Then let the JVM do the optimizing work for you.
I suggest you not try so hard at being clever. Spend some time looking at other code. Search Stack Overflow and elsewhere to find code similar to your logic problem or the classes you are using. Then study code samples.

Merging two lists of different type objects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having two lists of two different types of objects, which share some properties. Let us say List usersDb, and List usersLdap.
They share one property - userId. I want to merge usersDb and usersLdap into one list of another type of object (using some data from one list and some from second one). Important thing is that lists may be of different sizes. Then, that data should also be in final list, but fields from list that they did not occur in should remail null.
Could look like something like this (map the lists by user id, get all the user ids - or get the intersections of user ids, then go over all the user ids, get the matching value in each map, create your third type):
List<UserDb> listA = ...;
List<UserLdap> listB = ...;
Map<String, UserDb> a = listA.stream().collect(toMap(UserDb::getUserId, Function.identity());
Map<String, UserDb> b = listB.stream().collect(toMap(UserLdap::getUserId, Function.identity());
Set<String> allIds = new HashSet<>();
allIds.addAll(a.keySet());
allIds.addAll(b.keySet()); // Or retainAll if you want the intersection instead of the union
List<FinalType> = allIds.stream().map(id -> {
UserDb userDb = a.get(id);
UserLdap userLdap = b.get(id);
FinalType t = // Build this one from the 2 others. Be careful that either can be null
return t;
}).collect(toList());
First of all, it would improve performance to transform one of the Lists (let's say List<UserLdap>) to a Map<String,UserLdap> indexed by the userId (I assumed it's a String).
Now you can iterate over the other List, and for each element, search if the Map contains a matching element. Use those elements to create an instance of the merged type, and add to the output List.
Finally, you'll have to search the the List that was transformed to a Map for elements not having a corresponding element in the other List, transform them to the merged type, and add to the output List. For that final step to be efficient, it might be useful to create a Set<String> of all the userIds present in the other List.

Best practice for manipulating Collections [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Following situation:
I've created some methods, that allow me to manipulate a List. For a simple example these methods are addSomeElements(...) and removeSomeElements(...)
What is the best approch to call those methods? I know following ways to do that, but don't know which one's the best?!
1) re-initialize the list
private void doSomething(List<String> list) {
list = addSomeElements(list);
list = removeSomeElements(list);
}
In this case the methods would of course have to return a list:
private List<String> addSomeElements(List<String> list) {
list.add(...);
return list;
}
2) create new variables
private void doSomething(List<String> list) {
final List<String> list2 = addSomeElements(list);
final List<String> list3 = removeSomeElements(list2);
}
private List<String> addSomeElements(List<String> list) {
final List<String> newList = new ArrayList<String>(list);
newList.add(...);
return newList;
}
3) work with void methods
private void doSomething(List<String> list) {
addSomeElements(list);
removeSomeElements(list);
}
private void addSomeElements(List<String> list) {
list.add(...);
}
This would be the easiest way, but I don't really like it, because I think for the user it's not always obvious what you're doing. If you have an int for example, you would declare it like int myInt = 0. When you want to change the value, you could just say myInt = 1. It's clear that myInt has now a new value. But with the list it's different. The list you want to change might just be one of several parameters of the method you wanna call to modify the list. The user may probably not recognize that you've modified the list, which seemed to be only a Parameter, if the naming of the method doesn't tell it.
What would be the "cleanest" approach here?
If you're modifying the list passed into your method, don't return the list reference (your option #1 and option #2 since edited); it gives the impression at the API level that you're creating a new list, not modifying the one you were given.
That leaves you with two choices, either of which is "best practice" depending on context:
Modify the list passed in, and use void methods (or methods that return something else entirely if appropriate). (This is your option #3.)
Create new lists with the additions/removals, and return a reference to the new list. (This is like your edited option #2, but note that you would also have to return list3 out of doSomething for it to make sense.)
I recommend creating new lists instead of manipulating existing instances. Working with immutable state (which means copying state instead of modifying state) generally leads to cleaner code and less bugs. So I recommend going on the 2) way.
The mutable approach (modifying an existing list) may be faster, but don't go this way unless you have a very good reason to optimize.

Regarding Java Map and Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In Javascript, We can write statement as below.
var f_names = {
'a' : 'Apple',
'b' : 'Banana'
'c' : 'Carrot'
};
I can call this as f_names['c'] and get output as Carrot.
Is there any equivalent to this in Java instead of Map ? Similar to above ?
We can create an String array as bellow in java.
String[] names= { "Apple","Banana", "Carrot" };
Then can call as names[2] and this will return output as Carrot.
I'm looking for solution like this.
That is not at all conditional statement. It's Javascript object. In Java also there is Map.
Yes, you are just looking for Map in Java. Which stores key value pairs.
Map<String, String> map= new HashMap<String, String>();
map.put("a", "Apple");
map.put("b", "Banana");
And you can retrieve like
String a = map.get("a");// which results "Apple"
Update: If you are looking for other ways
Take a method which returns String. Add switch case inside method and
return the result value.
Take an array of array ex ({{k,v},{},{}}). Iterate to get the
required value.
Update after your latest comment :
(Both JS and Java are languages. if JS can achieve it as above(in simple way), why we use Map for that in Java.)
You are comparing two languages syntax, it's highly impossible to work with same syntax. If you still want to find the same way, the below would be the closest
HashMap<String, String > map = new HashMap<String, String>(){{
put("a", "Apple");
put("b", "Banana");
}};
Not sure about your acceptance of this cheat ;)
Syntax is a bit more complex in Java.
To get the closest equivalent, you can use a TreeMap, which will order its keys (default in this case is lexicographic order):
Map<String, String> names = new TreeMap<String, String>();
names.put("a", "Apple");
names.put("b", "Banana");
names.put("c", "Carrot");
System.out.println(names);
Output
{a=Apple, b=Banana, c=Carrot}
If you really don't want to use a Map, you can use a double-dimensional array.
For instance:
String[][] namesArray = new String[][]{{"a","Apple"},{"b","Banana"},{"c","Carrot"}};
System.out.println(Arrays.deepToString(namesArray));
Output
[[a, Apple], [b, Banana], [c, Carrot]]
Notes
Amongst the many advantages of using a Map is the fact that you can retrieve your values by key, which is probably something of interest given your context. For instance: names.get("A") will return "Apple.
With the array, you will need to retrieve your values by indices. For instance, namesArray[1][1] is "Banana".
Though Map is the thing you would really want, you could also use enums (I can't really help with those; I lack routine) and public static variables:
public final static String a = "Apple";
public final static String b = "Banana";
public final static String c = "Carrot";
Then they would be referencable from anywhere in the program. Say if the variables resided in a class named Fruits, they would be referenced to like this:
Fruits.a
Fruits.b
Fruits.c
This a Javascript Object(Java Script Object Notation) and it is more or less like a key-value pair. In Java this can be achieved by Map interface and the heavily used implementation of this interface is HashMap.

Categories

Resources