'Space efficiency of writing over temp data structures in java
using java for illustration, will the following code delete the previous instance of temp? or will it still be in memory for sometime until garbage collection takes care of it.
String[] words = {"one", "two" ,"three", "four", "five"};
for(String s: words){
// writing over temp each time
HashSet<Character> temp = new HashSet<Character>();
for(Character c : s.toCharArray()){
temp.add(c);
}
// do some computation with temp, afterwhich is no longer needed.
}
In my mind I am thinking that once temp has been written over its deleted pretty much straight away, making it efficient. Am i correct?
if not, is there a more space efficient way of making a temp data structure?
I understand that different languages have different garbage collection implementation, so would like to mainly know for java, however if there is a general rule for all languages that i could follow, that would be great
Solution 1:[1]
--- edit ---
The code below is not correct. But as other have commented, you can use a BitSet
If you are just talking about characters between a and z, the most efficient way you can do this is to use a bitmask, like
public class CharBitMask {
private int mask;
public void add (char c) {
mask = mask | (1 ^ ('a' - c));
}
public boolean contains (char c) {
return mask & (1 ^ ('a' - c)) == 1;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
