Delete all the data from 2D array of string in java - java

I have string array str[10][3], it is full of values.
Now I want to make it empty ie. delete all the values of str.
I have defined str as static, also I want empty this string from another claas in same package.
Can I use null here.
Plz suggest some way. thanks

Sure, you can use null but first wonder if you really need to nullify them, because null values will mostly generate problems and require special handling. You could use the empty string "" to avoid having problems with NullPointerExceptions.
Just reassign a new array to the same variable will do the trick, Java will take care about collecting garbaged data:
ClassName.str = new String[10][3];

str = new String[10][3]; will assign an empty 2D array to str.

One can always sets a value to null as long as it is no primitive type (int, char, boolean, ...) or a readonly value. I assume it's neither of them so the answer is YES.
So a solution would be:
str = null;
If you want to fill up your structure with new values you could use
str = new String[10][3];
however I don't see why you should do that, It's not because you don't need the data you should get rid of it. Furthermore in the new str there is also data (the initial null-strings). But if you wan't to store new data into the structure, there is no problem to do so. This paradigm is sometimes called "lazy". It means: "don't do anything unless you absolutly have to"
By setting null the data will not disappear at once. It is sheduled to be removed by the garbage collector. A program that only runs at some low frequency or if the program is in need of memory. In that case it wil mark the memory as free so it can be reused.

Related

Is it more efficient to put the 'new' in the put method, or use an intermediate variable?

Which of the below ways of adding to a HashMap is more efficient (considering both time and space efficiency)?
Way 1:
Music foo = new Music(Files.getMusic("bar/bold.mp3"));
HashMap.put("rock", foo);
Way 2:
HashMap.put("rock", new Music(Files.getMusic("bar/bold.mp3")));
Both are the exact same. When running
new Music(Files.getMusic("bar/bold.mp3"));
You create an object in memory, and return a reference to it. Whether you temporarily store that reference in foo before passing it to the HashMap or not doesn't really make a difference (and even if it would, this would be optimized away).
this is identical.
Java objects are passed by reference, you have the exact same number of objects created in both cases.

Is it possible to change a variables value from an array

This is a little confusing question for me to express, but I'll do my best.
So:
ArrayList<Object> fieldList = new ArrayList<Object>();
I then dump a lot of different variables to this array:
fieldList.add(objectsURL); //string
fieldList.add(X); //int
fieldList.add(Y); //int
...
If I change the variable, the values in the array change
too-confirming the array stores a reference to the memory, rather
then value itself.
However, if I then retrieve data from the array then set that...
Object object = ((String)this.fieldList.get(0));
Then set object
object = "meeep!"
objectsURL is not set to "meep!" but rather it retains its original
value.
I assume this is because the "object" is not referencing the original
variable anymore, that instead its pointing to a new immutable string
in the memory.
All expected Java behavior I think....but then, how would I go about
setting the actual original variable? is this possible in java?.
So, in other words. Given only access to "fieldList" is it possible to change the value of
"objectsURL"?
So, if:
String objectsURL = "www.google.com"
fieldList.add(objectsURL);
Is there a way to set objectsURL to "www.stackoverflow.com" using only a reference from fieldList?
I dont want to change the fact that fieldList contains "objectsURL", I want to change what string the variable "objectsURL" actualy contains.
If not, is there an alternative method to achieve the same thing?
I hope my question explains the problem well enough.
My use-case is trying to make a serialization/
deserialization system for a bunch of my objects. I was hoping to put
all the fields into a arraylist I could retrieve for both reading and
writing....thus avoiding having to hard-code long lists of
field[0]=blah and blah=field[0] and then going though constant pains
of needing to renumber them each time I add a new field before
another.
(I cant use Javas inbuilt serialization, as I am using GWT and this is client side only.)
Thanks,
I assume this is because the "object" is not referencing the original variable anymore, that instead its pointing to a new immutable string in the memory.
Correct, each time you use the assignment operator = on an object you change the object it refers to, not the object itself.
To change the values in the List, you use the .set method of an ArrayList
this.fieldList.set(0, newValue);
Since your variable is a String, there is no way you can change the String-variable through the list
Your alternatives:
using a char-array
List myList = new ArrayList();
char[] charArray = "My String".toCharArray();
myList.add(charArray);
charArray[0] = 'A';
String theString = new String(myList.get(0)); // "Ay String"
If you use a char-array, make sure that the length of the array is enough to contain the number of characters you want to have in the future, because to change the length of the array you will need to create a new array (array lists can be expanded dynamically, arrays can not)
Embed the String inside your own class (I have ignored getters and setters here)
class MyString {
public String value;
public MyString(String value) {
this.value = value;
}
}
MyString myStr = new MyString("some value");
list.add(myStr);
((MyString) list.get(0)).value = "a new value";
System.out.println(myStr.value); // will print "a new value"
Strings are immutable, so it is impossible to change the contents of a String object. Also, you cannot use the list to change what object the reference variable objectsURL points to. To achieve what you want, you will need to create a custom class that has a String member. You can then store instances of this class in a List and change the String references to via the references in the list. The changes will then be reflected in any other reference variables which refer to the objects in the list.
First, you declare a variable 'object' and assign some Object out of the ArrayList. Later you assign some other object "meeep!" to this variable. There is no reason that your 'object' variable is related to the ArrayList.

What's best for array reinitialization : set to null by iteration or simply allocate a new array?

In my code, I have an array that has about 1000 elements :
Object[] arr = new Object[1000];
After my array is populated (the whole array or just partially), I need to reinitialize it. From what I know, I have two choices : to initialize it by new keyword, or to iterate over it and set each element to null. I think first approach is best than second, but also I'm waiting for your thoughts.
Any links or articles on this topic are welcome.
Thanks in advance
First one is better. By reinitializing it with new keyword, you put the previous set of array eligible for garbage collection by providing a path to GC (assuming that other live objects does not have a reference to any of them).
The second one would achieve the same effect eventually, but there is an added performance hit because you need to iterate one by one. For 1000 records, this would likely happen very fast, but if the number grows then the hit would be greater.
Agree with your first choice use arr = new Object[1000] and don't loop it.
Also the use of new Object[1000] doesn't create 1000 objects it only makes a "placeholder" for 1000 objects so it's a very cheap operation.
And if you know you will populate all 1000 objects you can just use the array as is without reinitializing it.
First is the best way Object[] arr = new Object[1000];
also you can find in below link, number of ways array can be initialised
array initialisation
First by setting the array to null you effectively tell the GC it can check everything in that array and clean it up if necessary. So there is no need to iterate through the elements, even if you arent going to do a new right away.
That being said, the only time you really would ever explicitly need to set a variable(for GC purposes anyway) to be explicitly NULL is if you no longer need the data pointed to by that variable, but have nothing new to put in its place AND the variable, for whatever reason, will stay in scope for a while. In that case its advisable to set the value to null, or better yet, re-work your code so that variable goes out of scope and that is done for you.
So for instance, in your example say arr was a static member of some class and you just needed to do some processing on the array at startup and never look at it again. In that case, the contents of arr will stick around for the entire time your program is running UNLESS you explicitly set it to null(or assign it a new value).

Null pointer when moving data around

I've got a function filling a HashMap(rMap) of String arrays. Once certain conditions are met e.g r.Map.size() != 0 I then, in another file (rMap is a Global variable) call the following String array[] = rMap.get(0) from this I attempt to System.out.println(array[0]) .
Thats the run of the program and I get a null pointer at System.out.println(array[0]);. Anyone have any ideas why this happens?
EDIT: I'm filling the map like so..
String center[] = new String[] { tname, tmessage, tlink, tsname };
Global.rMap.put(index, center);
Where all values in the array are variables that are strings. So the value I'm accessing it tname and It's not equal to null. I've checked. My Key value is a String
The array reference is null, most likely because no value (or a null) has been added to rMap, with key 0.
If possible, use generics to ensure that your keys are the correct type. You might also print out the values of the map prior to fetching array to see what is in the map. Stepping through the code with a debugger, with a watch on the rMap will also show what the map contains and when it is changed.
How are you filling the map? Are you certain that you're putting an non-null entry with an Integer key of 0 into it?
Well, we can be pretty certain that you aren't. Possible reasons:
An error in the filling code that results in the intended put not being executed, or with a different key value
You're using Short or Byte objects as keys
You're putting a null value into the map under the 0 key
You can answer this question for yourself by running the code in a debugger and looking at the contents of the map.
Update:
My Key value is a String
Well, that's your problem right there. rMap.get(0) will look for an Integer, and it will not match the entry for a String "0".
HashMap allows null values, so the value you are getting with String array[] =rMap.get(0); may be null. Accessing the null array then throws the NPE.
Try rMap.get(Integer.valueOf(0));
It's an issue when you invoke the get method of Map implementation, the signature of get method of java.util.Map is get(java.lang.Object),thus,any object will be accepted as its argument.
The key that works fine is either pass a string(value=0) as a key or overrides the hashCode and equals methods of argument object that is not a java.lang.String object.
The get() method of Hashmap takes a key, not an index, to identify the value you want to get. If you want an ordered list of items, you'll need to use a List subclass (or enforce the ordering, yaourself). If you want to use a Hashmap, use the keys() method to get an enumeration of all the map's keys.
(removed above text, due to question clarification. leaving below text as, even though it's not the problem, it is an important consideration)
Also, you'll need to be very careful not to create race conditions, since you're working across threads. While Java's native Hashtable is synchronized, that doesn't mean the data in it is. That is, you can MyObj obj = get(xxx) in one htread, Nd start manipulating the obj in two separate threads, possibly stepping on each other. Depending upon your application, you may want to use Hashtable.remove() so that the data is gone from the map and cannot be re-used, or you may need some synchronized blocks (remove() may well be the simpler implementation, thoguh you'd have to gracefully handle conditions where the map first has data, then that data is gone).

Use of array of zero length

For example we can construct such an array like this:
new ElementType[0];
I seen such a construct, but I don't understand why this might be useful.
An example. Say, you have a function
public String[] getFileNames(String criteria) {
to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.
The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).
There's a chapter on this in Effective Java, Item 27
It's easier to work with than null in many cases, where null is the obvious alternative.
Suppose you want to return an Iterable<String> containing (say) a list of relevant filenames... but there aren't any for some reason. You could return null to indicate that, but then the caller has to special-case that. Instead, if you return an empty collection, the caller can still use an enhanced for loop:
for (String file : getFiles())
So why use an empty array instead of an empty ArrayList or something similar? Arrays are a fixed size, so an empty array is effectively immutable. That means you can keep a single value and return it to whoever you like, knowing they can't possibly do anything with it. That can be very useful in some situations.
it is a replacement for null since you don't need to check for null before use it.
More formally it is a special case of special case design pattern (check also Null Object).
Another idiomatic use is collections toArray:
List<String> list = new ... ;
// fill the list
String[] array = list.toArray(new String[0]);

Categories