3

I have question about primitive types in Java (int, double, long, etc).

Question one:

Is there a way in Java to have a datatype, lets say XType (Lossless type) that can hold any of the primitive types? Example of hypothetical usage:

int x = 10;
double y = 9.5;
XType newTypeX = x;
XType newTypeY = y;

int m = newTypeX;

Question two:

Is there away to tell from the bits if this number (primitive type) is an integer, or a double, or a float, etc?

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
MacBeast
  • 33
  • 5
  • 4
    Do you mean [the Numbers classes](https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html) which are wrappers for Java primitives? [`Number`](http://docs.oracle.com/javase/7/docs/api/java/lang/Number.html) is the super type for all number wrappers, so because of auto-boxing, replacing `XType` with `Number` should work ok. – Mick Mnemonic Jul 24 '15 at 00:21
  • 1
    Question two is answered here: http://stackoverflow.com/questions/1891595/check-type-of-primitive-field – MrMadsen Jul 24 '15 at 00:22

6 Answers6

4

You can use the Number class, which is the super class for all numeric primitive wrapper classes, in your first snippet:

int x = 10;
double y = 9.5;
Number newTypeX = x;
Number newTypeY = y;

The conversion between the primitive types (int, double) and the object type (Number) is possible through a feature called autoboxing. However, this line won't compile:

int m = newTypeX;

because you cannot assign the super type variable into an int. The compiler doesn't know the exact type of newTypeX here (even if it was assigned with an int value earlier); for all it cares, the variable could as well be a double.

For getting the runtime type of the Number variable, you can e.g. use the getClass method:

System.out.println(newTypeX.getClass());
System.out.println(newTypeY.getClass());

When used with the example snippet, this will print out

class java.lang.Integer
class java.lang.Double
Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30
  • Autoboxing came with Java 5.0, before you would have to write `Number x = new Integer(10);` To get the type you can use `instanceof`, but it will become an ugly `if`. Overloading methods might be better than using `Number` depending on the situation. – maraca Jul 24 '15 at 01:05
0

Well, you can do something like this:

Integer i = 1;
Float f = 2f;
Object[] obArr = new Object[]{i, f};
Float fReconstruct = (Float) obArr[2]

Not really primitive types, but the closest you can get!

Roberto Anić Banić
  • 1,411
  • 10
  • 21
0

Regarding to your first question, for those you can use the Number class.enter image description here

Gonz
  • 1,198
  • 12
  • 26
0

You can use an Object to hold reference to any of these types, but it will be 'boxed' to it's wrapper (int will be hold as an Integer, long as a Long, etc.)...

Eldius
  • 310
  • 2
  • 4
0

Not yet (java 8), and not in the way you want to get the primitive value back. But if instead of holding a primitive type you hold a primitive type wrapper (which are classes that descend from the Object class and wrap their corresponding primitive, i.e. Byte wraps byte, Integer wraps int, Long wraps long, etc), then you could do this:

public class Holder<T extends Number> {

    private final T number;

    public Holder(T number) {
        this.number = number;
    }

    public T get() {
        return this.number;
    }
}

You could use this Holder class to hold an instance of any subclass of Number, including primitive types wrappers. For example:

Holder<Integer> holderX = new Holder<>(5);
Holder<Double> holderY = new Holder<>(1.234);

int x = holderX.get(); // 5
double y = holderY.get(); // 1.234

The above is possible because of a feature of Java called Generics, along with another feature called autoboxing.

Extending generics to support primitive types is being considered for Java 9 or 10 (not sure), under the term Specialization. In theory, this would allow you to have:

List<int> list = new ArrayList<int>();

Here is a draft.

fps
  • 33,623
  • 8
  • 55
  • 110
-1

Generics are a facility of generic programming that were added to the Java programming language in 2004 within J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety.

For an example I like the one on tutorialspoint:

public class GenericMethodTest
{
   // generic method printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}

This would produce the following result:

Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 

Array characterArray contains:
H E L L O    Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 

Array characterArray contains:
H E L L O

For more on this link.

CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186