Determining available operators at runtime - java

I would like to be able to retrieve the available operators for an object at runtime, possibly in a similar way as the getMethod() call.
In particular, I need to be able to call the less-than/greater-than operators of an object at runtime.
Basically, I have a bunch of primitives that have been cast to the Object object-type. I need to perform comparisons between them at run-time. (I do know that the objects being compared will be of the same original type, and have implemented my own type-checking).
Alternatively.. Maybe there is a way to programatically cast these objects back to their original type, and use their native comparison operators.. somehow?
Thanks for any assistance.

There is no way in Java to get available operators. For comparison the class should (you may do this thru reflection also) implement the Comparable interface.

If they are auto-boxed primitive types, the set of arithmetic operators is identical for all types other than Boolean, and the set of bitwise operators ditto apart from the two FP types.

Related

Why Java doesn't support structures ? (Just out of curiosity)

I know you can use public fields, or some other workarounds. Or maybe you don't need them at all. But just out of curiosity why Sun leave structures out.
Here's a link that explains Sun's decision:
2.2.2 No More Structures or Unions
Java has no structures or unions as complex data types. You don't need structures and unions when you have classes; you can achieve the same effect simply by declaring a class with the appropriate instance variables.
Although Java can support arbitrarily many kinds of classes, the Runtime only supports a few variable types: int, long, float, double, and reference; additionally, the Runtime only recognizes a few object types: byte[], char[], short[], int[], long[], float[], double[], reference[], and non-array object. The system will record a class type for each reference variable or array instance, and the Runtime will perform certain checks like ensuring that a reference stored into an array is compatible with the array type, but such behaviors merely regard the types of objects as "data".
I disagree with the claim that the existence of classes eliminates the need for structures, since structures have semantics which are fundamentally different from class objects. On the other hand, from a Runtime-system design perspective, adding structures greatly complicates the type system. In the absence of structures, the type system only needs eight array types. Adding structures to the type system would require the type system to recognize an arbitrary number of distinct variable types and array types. Such recognition is useful, but Sun felt that it wasn't worth the complexity.
Given the constraints under which Java's Runtime and type system operate, I personally think it should have included a limited form of aggregate type. Much of this would be handled by the language compiler, but it would need a couple of features in the Runtime to really work well. Given a declaration
aggregate TimedNamedPoint
{ int x,y; long startTime; String name; }
a field declaration like TimedNamedPoint tpt; would create four variables: tpt.x, tpt.y of type int, tpt.startTime of type long, and tpt.name of type String. Declaring a parameter of that type would behave similarly.
For such types to be useful, the Runtime would need a couple of slight additions: it would be necessary to allow functions to leave multiple values on the stack when they return, rather than simply having a single return value of one the five main types. Additionally, it would be necessary to have a means of storing multiple kinds of things in an array. While that could be accomplished by having the creation of something declared as TimedNamedPoint[12] actually be an Object[4] which would be initialized to identify two instances of int[12], a long[12], and a String[12], it would be better to have a means by which code could construct a single array instance could hold 24 values of type int, 12 of type long, and 12 of type String.
Personally, I think that for things like Point, the semantics of a simple aggregate would be much cleaner than for a class. Further, the lack of aggregates often makes it impractical to have a method that can return more than one kind of information simultaneously. There are many situations where it would be possible to have a method simultaneously compute and report the sine and cosine of a passed-in angle with much less work than would be required to compute both separately, but having to constructing a SineAndCosineResult object instance would negate any speed advantage that could have been gained by doing so. The execution model wouldn't need to change much to allow a method to leave two floating-point values on the evaluation stack when it returns, but at present no such thing is supported.

Why does a key in a Map must be an object and not a primitive and Why cant i use primitive type as key in a map

I have a map: Map abc = new HashMap(). Why is it mandatory for me to use only objects as keys and not primitives?
As for why: The implementations of a Map require Object keys (with an equals() function) to (efficiently) order/store your values for quick retrieval. Primitives do not have an equals() function and are therefore unsuited for the task. (this is basically what #MadProgrammer suggested, except that equals is used in the defintion, and hashCode is just optional for possible implementations).
There is no reason that it would not be possible to programm this, however: in fact you could argue that primitives have the easiest equality and hashCodes to compute! This is probably what is done in TIntArrayList as suggested by Narendra Pathai. And as Jens Schauder states: it would not be worth the hassle, also because autoboxing hides the problem from you most of the time.
In java there is a big divide between primitives and objects/classes.
When you define a method that takes and Object as an argument, you might as well pass a String, or a AbstractSingletonFactoryFacade. But you can't pass a primitive. There is just no way to abstract over multiple primitives. This didn't change with generics.
What one could do is define separate interfaces accepting (and returning) the various primitives. While this would be feasible for thing like List, which have only one type parameter, for Map with two type parameters you would end up with 81 interfaces (8 primitive types + Object squared). Which just isn't worth the hassle.
Of course most of the time this doesn't matter since Autoboxing makes the problem invisible most of the time.

When should I use Boolean instead of boolean? [duplicate]

This question already has answers here:
Boolean vs boolean in Java
(8 answers)
Closed 9 years ago.
When should I use Boolean instead of boolean?. I mean, why would I want to have a null value in a variable which should contain either "true" or "false".. One spontaneous answer (of most people) would be if the value is unknown. i.e, if we don't know whether the value is true or false. But from a programming perspective, I think using Boolean may break the code as we will not know whats inside. So, I think using the primitive type is better than the wrapper.. Correct me if I am wrong.
Generally speaking, the wrapper classes are used in cases where an object is required or strongly preferred. Outside of these situations, it's better to use the primitive types, since they have lower overhead, you can use ==, etc. There are two and a half major situations where this is frequently seen:
Collections. This is now a subset of the next case, but even before Java 5 the Collections classes only supported objects as keys and values, and this hasn't changed.
Generics. Generic types can only work with objects, not primitives, and so if you're using "boolean" as a type parameter, it has to be the wrapper class. For example, if you're using a Future, you have to use a Boolean instead of a boolean. (HT #user949300)
ORM. JPA and other ORM systems technically can use primitive fields, but it's customary to use the wrapper classes, since the overhead is high enough that that doesn't really matter anyway, and the wrapper classes can represent a NULL value that might be present in the database. It's usually still better to forbid nulls and use a primitive for booleans, though, since semantically a default is usually better than "undefined".
Since boolean values are restricted to either true or false, it's uncommon to see them used in Collections or Generics; generally speaking, if you'd have a boolean as a value, you'll just use Collection#contains instead.
IMHO the primitive is better.
Always favor primitives over wrappers. Wherever I am able to use primitives, I go for them because at run time, if we use wrappers, boxing conversions and unboxing conversions happen, and obviously that takes more time. If you use the primitive there, you save that time.
And as usual it depends on your requirements whether you need a Object (which can be null) or you can use a primitive (which cannot be null) in your situation.
For example: Assume you are dealing with collection's then you have no option's,You have to use wrappers :).
Boolean have 3 possible values (null, true, false) while boolean can only be (true, false).
I greatly prefer primitives. However, Booleans are necessary:
When they go into Collections
When you need to allow for a null value. In my experience, this is mainly if they are stored in a database and you need null to indicate that they haven't been read yet, or the user hasn't filled in some form yet.
What if you need to use collections?
Collection will not store primitive types, you need to store object there.
Collections provide so many utility apis, so if you want to use them them a Boolean object is need as collection will need objects.
Although you can always use autoboxing which means you are shielded from object creation and collection takes care of it internally.
Boolean is an object, so you can use it with generics. For example, you can have Map<String,Boolean> to store a true\false value for each string(=key). You can't do Map<String,boolean>, because boolean is not an object - specifically, it's not a subclass of Object. Generics are compile-time wrappers, so Map<Foo,Bar> is actually Map<Object,Object> with smart casting, no matter what Foo and Bar are - as long as they are classes or array types. But they can't be primitives.
The Wrapper classes will be in cases where an object is required or strongly preferred like storing the objects in Collections, cache or session etc, where it requires an object (if not, JRE will convert the primitives to Wrapper classes before they are stored in secondary cache). The below link will explain in better:
Boolean vs boolean in Java
Booolean is an object/reference type that wraps a boolean whereas boolean in a primitive type.
Boolean - You would get more methods which will be useful.
boolean - Will save you lot of memory. But if you use Boolean.valueOf(value) of new Boolean(value), that shouldn't be a cause.
Converting between primitives and objects like this is known as boxing/unboxing.
Click on the below links for more info:
http://javaeye.wordpress.com/2008/06/17/boxing-and-unboxing-conversion/
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
http://www.javapractices.com/topic/TopicAction.do?Id=197

TreeMap that contains String as key and a boolean as value?

Hello I tried to create a TreeMap in Java but the compiler gives the error saying "unexpected type".
Can anyone tell me why? Isn't possible to have primitive data types in a Map?
I did solve it by using the java.lang.Boolean instead. But I don't understand why I can't mix a complex data type with a primitive one.
To answer your query,
Maps and other classes which are treated as collections not only serve the purpose of storing data but they also provide methods for comparing. In java comparators are used for the same. In short you need to call methods on the objects you want to compare. If the values are primitive data type, no methods can be invoked on them. This is precisely one of the major reasons why primitive data types are not permitted in collections and related classes.
hope this helps
Isn't possible to have primitive data types in a Map?
No, it isn't. Try <String, Boolean>.
But I don't understand why I can't mix a complex data type with a primitive one.
It's not about mixing complex data types with the primitive types.
The reason is that none of the classes in the Java Collection Framework are designed to support primitive types.
If you need to use any primitive type with the collection framework then you have to use the corresponding wrapper class. e.g. Integer for int ...
Only array supports primitive types.
Isn't possible to have primitive data types in a Map?
No. You cannot use primitive types at all in Java generics.

In Java, why are arrays objects? Are there any specific reasons?

Is there any reason why an array in Java is an object?
Because the Java Language Specification says so :)
In the Java programming language arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
So, unlike C++, Java provides true arrays as first-class objects:
There is a length member.
There is a clone() method which overrides the method of the same name in class Object.
Plus all the members of the class Object.
An exception is thrown if you attempt to access an array out of bounds.
Arrays are instanciated in dynamic memory.
Having arrays be objects means that you can do operations with them (e.g., someArray.count('foo')) instead of just doing it against them (e.g., count(someArray, 'foo')), which leads to more natural syntax.
Another point is that objects are mutable and are passed by reference. In arrays there aren't any fields/methods that you can use to change "properties" of the array, but you sure can mutate the element values. And the benefits of passing arrays by reference are pretty obvious (though functional programmers probably wish Java had immutable lists passed by value).
Edit: forgot to mention. In the period before autoboxing, it was helpful to be able to store arrays in collections, write them to ObjectStreams etc.
Probably because they wanted to get as close as possible to making everything an object. Native types are there for backward compatibility.
So that they get all the benefits thereof:
getHashCode()
toString()
etc.
And arrays aren't 'primitive', so if they can't be primitive, they must be objects.
I'm not sure about the official reason.
However, it makes sense to me that they are objects because operations can be performed on them (such as taking the length) and it made more sense to support these operations as member functions rather than introduce new keywords. Other operations include clone(), the inherited operations of object, etc. Arrays are also hashable and potentially comparable.
This is different from C (and native arrays in C++), where your arrays are essentially pointers to a memory offset.

Categories

Resources