How to set individual element of an array to Empty [duplicate] - java

How do I define a Null string, date or integer in VBA?
I need to be able to assign a Null value to some fields for certain records when data is incomplete or irrelevant, but if I declare a variable as a String, Date or Integer, I get errors when trying to assign a Null value.
Is the only solution to use Variant? If so, then what is the point of all other datatypes in VBA?

Dim x As Variant
x = Null
Only the Variant data type can hold the value Null.
A Variant is a special data type that can contain any kind of data [...] A Variant can also contain the special values Empty, Error, Nothing, and Null.
The "point" of all the other data types is precisely that they cannot contain any ol' kind of data. This has two advantages that I can think of:
It's more difficult for the programmer to assign data of an unintended type to the variable by mistake, since this will be detected at compile time. This can help prevent bugs and make things clearer for you and the next person who will be maintaining your code.
Narrow data types save storage space. Putting integers in a Variant (16 bytes) takes up way more memory than putting them in an Int (2 bytes). This becomes significant if you have large arrays.
Of course, Variants do have their place, as other threads on this site discuss.

Related

Java object arrays memory requirements

Suppose there is an Integer array in my class:
public class Foo {
private Integer[] arr = new Integer[20];
.....
}
On a 64 bit architecture the space requirement for this is ~ (20*8+24) + 24*20 {space required for references + some array overhead + space required for objects}.
Why java stores references to all of the 20 Integer objects? Wouldn't knowing that first memory location and the number of items in the array suffice? (assuming and I also as I read somewhere that objects in an array are placed contiguously anyways). I want to know the reason for this sort of implementation. Sorry if this is a noobish question.
Like every other class, Integer is a reference type. This means it can only be accessed indirectly, via a reference. You cannot store an instance of a reference type in a field, a local variable, a slot in a collection, etc. -- you always have to store a reference and allocate the object itself separately. There are a variety of reasons for this:
You need to be able to represent null.
You need to be able to replace it with another instance of a subtype (assuming subtypes are possible, i.e. the class is not final). For example, an Object[] may actually store instances of any number of different classes with wildly varying sizes.
You need to preserve sharing, e.g. after a[0] = a[1] = someObject; all three must refer to the same object. This is much more important (vital even) if the object is mutable, but even with immutable objects the difference can be observed via reference equality checks (==).
You need reference assignment to be atomic (cf. Java memory model), so copying the whole instance is even more expensive than it seems.
With these and many other constraints, always storing references is the only feasible implementation strategy (in general). In very specific circumstances, a JIT compiler may avoid allocating an object entirely and store its directly (e.g. on the stack), but this is an obscure implementation detail, and not widely applicable. I only mention this for completeness and because it's a wonderful illustration of the as-if rule.

Make default value of a "Short[]" element 0 instead of null?

I have a program that creates lists and needs any assigned values to be 0. Its been running fine when I do with int[] humpty_dumpty = new int[20]; but to optimize the size of the lists I set them to Short[] and now my program is breaking because it takes the zero's as inputs(and Short[] humpty_dumpty = new Short[20]; is making the default value null).
Is there a way to set it to default zero without having to iterate through the entire list(I can do this via a for loop but was wondering if there was a way to make its behavior similar to int)?
There is a difference between a Short[] and a short[]. Elements of the latter will be initialized to 0 because short is a "primitive" type and cannot be null. The capitalized Short class will be initialized to null because it is really just an Object wrapping a short value.
You may create an array of primitive type instead of wrapper,
short []ar=new short[20];
Short[] doesn't 'optimize the size of the lists' at all, and it has a default value of null. short[] does, and it has a default value of zero.
Answers, in order:
1) Requirement first, optimization last. Don't use sparse arrays, or try to be 'smart', unless you specifically need to do this & deal with the extra code/ overhead.
2) Use common methods (possibly in an Instance or Static Helper class) to avoid repeating common code.
eg. short sparseGet (Short[] array, int i) {return (array[i] != null ? array[i] : 0);}
3) Perhaps use short[] rather than Short[]? Uppercase types are not primitives, but Value Wrapper classes -- and stored as object references (pointers) to instances, thus slower & more memory-intensive.
4) Uppercase 'Value Wrapper' types are appropriate where you may have null values, from a database. eg. Person.Age would ideally be Integer, if there's any possibility you/ the database might not have data for that field.
Cheers.

static method - when to return an array argument as void and return as an array?

I've been reading this section about static methods and about passing arrays by call-by-reference. So my question is: When is it ever a good time to return an array argument as an array as opposed to void?
Thanks in advance!
I've been reading this section about static methods passing arrays by call-by-reference.
If this is a Java article, site, blog, book, whatever, you should probably find a better one. Java doesn't use "call-by-reference" on any parameters. Anyone who says that either doesn't understand Java, or doesn't understand what "call by reference" means.
Java passes all arguments by value. Period.
The point of confusion is that some people don't understand that Objects and arrays in Java are always references. So when you pass an array (for instance) as an argument, you are passing the reference to the array by value. However, this ins NOT a nitpick. Passing a reference by value is semantically very different to true "call by value".
Re the actual quote:
"All of these examples highlight the basic fact that the mechanism for passing arrays in Java is a call by reference mechanism with respect to the contents of the array" (Sedgewick).
I understand what he is saying, given the qualification " with respect to the contents of the array". But calling this "call by reference" is misleading. (And clearly, you were mislead by it, to a certain degree!)
I would also argue that it is technically wrong. The terms "call-by-value", "call-by-reference", "call-by-name" (and so on are) about parameter passing / returning. In this case, the parameter is the array as a whole, not the contents of the array. And at that level, the semantics are clearly NOT call-by-reference. (Assigning a new array reference to the parameter name in the method does not update the array variable in the caller.) The fact that the behaviour is not distinguishable from call-by-reference with respect to the array contents does not make it call-by-reference.
Now to the meat of your question ...
When is it ever a good time to return an array argument as an array as opposed to void?
It is not entirely clear what you mean, but I assume that you are talking about these two alternatives:
public void method(String arg, String[] result) ...
versus
public String[] method(String arg) ...
I'd say that the second form is normally preferable because it is easier to understand and to use. Furthermore, the second form allows the method to choose the size of the result array. (With the first form, if the array is too small or too large, there is no way to return the reference to a reallocated array.)
The only cases where the first form should be used are:
when the functional requirements for the method depend on it being to update an existing array, or
when there is an overarching need to minimize the number of objects that are allocated; e.g. to minimize GC pauses.
The first case might arise if the array is already referenced in other data structures, and finding / updating those references would be difficult. It also might arise if the array is large, and the cost of making a copy would dominate the cost of the real work done by the method.
All parameters passed into a method in java are reference expect the primitive type, so wherever inside or outside the method it just keeps one object storage in memory, Static method are even NOT treated as any special case here. In your case of returning this array or a void type, it would not make any differences.
If you return this array, the returned value is what exactly you just now passed into this method.
WELL, ultimately... passing an array by value is slow. It has to grab a block of memory and copy the array. If the array is only a few bytes in size, its not a big deal. But if its a large chunk of memory, then this will be a slow IO operation. ESPECIALLY if this is happening in a tight loop, it will hurt performance.
Passing by reference will allow you to create a buffer ahead of time and reuse it.

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).

When to use primitive and when reference types in Java

In which case should you use primitive types(int) or reference types (Integer)?
This question sparked my curiosity.
In which case should you use primitive
types(int) or reference types
(Integer)?
As a rule of thumb, I will use a primitive (such as int) unless I have to use a class that wraps a primitive.
One of the cases were one must use a wrapper class such as Integer is in the case of using generics, as Java does not support the use of primitive types as type parameters:
List<int> intList = new ArrayList<int>(); // Not allowed.
List<Integer> integerList = new ArrayList<Integer>(); // Allowed.
And, in many cases, I will take advantage of autoboxing and unboxing, so I don't have to explicitly perform conversions from primitives to its wrapper class and vice versa:
// Autoboxing will turn "1", "2", "3" into Integers from ints.
List<Integer> numbers = Arrays.asList(1, 2, 3);
int sum = 0;
// Integers from the "numbers" List is unboxed into ints.
for (int number : numbers) {
sum += number;
}
Also, as an additional note, when converting from primitives to its wrapper class objects, and unique instances of objects are not necessary, use the valueOf method provided by the wrapper method, as it performs caching and return the same instance for a certain value, reducing the number of objects which are created:
Integer i1 = Integer.valueOf(1); // Prefer this.
Integer i2 = new Integer(1); // Avoid if not necessary.
For more information on the valueOf methods, the API specification for the Integer.valueOf method can serve as a reference for how those methods will behave in the wrapper classes for primitives.
That really depends on the context. First prefer the primitive, because it's more intuitive and has less overhead. If it is not possible for generics/autoboxing reasons, or if you want it to be nullable, then go for the wrapper type (complex type as you call it).
The general rules I follow when creating an API can be summarized as follows:
If the method must return an value, use a primitive type
If the method may not always apply (eg: getRadioId(...) on an object where such an ID may not exist), then return an Integer and specify in the JavaDocs that the method will return null in some cases.
On #2, look out for NPEs when autoboxing. If you have a method defined as:
public Integer getValue();
And then call it as follows:
int myValue = getValue();
In the case where getValue() returns null you'll get an NPE without an obvious cause.
Since Java does something called auto-boxing and auto-unboxing, you should use the primitive type int in most cases because of less overhead.
The only time you absolutely need to use Integer is in generics.
List<int> list; // won't compile
List<Integer> list; // correct
One case in which Integer might be prefered is when you are working with a database where numerical entries are allowed to be null, since you wouldn't be able to represent a null value with an int.
But of course if you're doing straight math, then int would be better as others have mentioned due to intuitiveness and less overhead.
My rule of thumb is: use boxed primitives only when it's necessary to get the code to compile. The only places in your code where the names of the primitive wrapper classes should appear is in generic type parameters and static method calls:
List<Integer> intList = new ArrayList<Integer>();
int n = Integer.parseInt("123");
That's the advice I would give to new Java programmers. As they learn more, they'll run into situations where they have to be more discerning, like when dealing with Maps or databases, but by then they should also have a better understanding of the difference between primitives and boxed primitives.
Autoboxing tempts us to believe int and Integer (for example) are interchangeable, but it's a trap. If you mix the two kinds of value indiscriminately, you can end up comparing two Integer values with == or trying to unbox a null without realizing it. The resulting bugs can be intermittent and difficult to track down.
It doesn't help that comparing boxed primitives with == sometimes works as if it were doing a value comparison. It's an illusion caused by the fact that values within a certain range are automatically cached in the process of autoboxing. It's the same problem we've always had with String values: comparing them with == sometimes "works" because you're actually comparing two references to the same, cached object.
When dealing with strings we can just tell the n00bs never to compare them with ==, as we've been doing all along. But comparing primitives with == is perfectly valid; the trick (thanks to autoboxing) is being sure the values really are primitives. The compiler will now let us declare a variable as an Integer and use it as if it were an int; that means we have to exercise a greater level of discipline and treat it as an error when someone does so without good reason.
Rather than calling them "complex types", you'd be best served thinking Integer, Double, etc. as "Classes", and int, double, etc. as "primitives".
If you're doing any type of sophisticated math, the Class-based numeric representation like Integer and Double will be cumbersome and slow you down - many math operations can only be done with primitives.
On the other hand, if you're trying to put your numbers into collections like Lists and Maps, those collections can only contain objects - and thus you must use (or convert to) classes like Integer and Double.
Personally, I use primitives whenever I can get away with it, and only convert to the Class representations like Integer when it's time to do input or output, and the transport requires those representations.
However, if you aren't doing any math at all, and instead are just passing the values straight through your code, you might save yourself some trouble by dealing with the Class-based forms (like Integer) exclusively.
I think this is a bit late but I wanted to add my opinion just in case.
in some scenarios, it's required to use the wrappers as the lack of a value is different from the default value.
example,
for one project I worked on, there was a field on screen where the user could enter a double value, the business requirement clearly mentioned that if the user enters a 0 the meaning is different from not entering a value and leaving the field blank and this difference will make an impact later on in a different module.
so in this scenario we had to use the Double object, since I cannot represent a lack of value using the primitive; since the primitive will default to 0 which was a valid input for the field.
I dont think there is any rule as such. I would choose the types over primitives (Integer over int) when I write method signatures, Maps, collections, Data Objects that get passed around. As such I would still like to use Integer instead of int even inside of methods etc. But if you think that is too much trouble (to type extra "eger") then it is okay to use ints for local variables.
If you want to setAttribute to session you have to use Object like Integer,Boolean,String in servlets. If you want to use value you can use primitive types. Objects may be null but primitives not. And if you want to compare types for primitives use == but objects use .equals because in object comparision == looks not values it looks if these are the same objects. And using primitives makes faster the code.
When we deal with Spring getRequest mapping methods, using boolean value does not work.
For instance :
#GetMapping("/goal")
public boolean isValidGoal() {
boolean isValid = true;
return isValid;
}
Always opt for Boolean in those cases.

Categories