Related
I'm trying to make a method that accepts a number of any primitive type (either byte, int, float, long, double or short). Then after a certain checking method either returns that very same number (i.e., for example, it accepts double and returns double) or it returns a zero.
So far I've come to this:
<AnyNumType> AnyNumType cancelAdd(AnyNumType val, String point) {
if (checkModuleMatchAndOff(point) == true) return 0;
else return val;
}
But I get a type mismatch error (with 0 underlined and explained: "Cannot convert from int to AnyNumType"). Is there a way to cope with this zero problem? I intend to use this method in equations so I really need it to return primitive types.
EDIT: Thank you very much for all your replies, guys!
No, you're not accepting any primitive type; you're accepting any object type. You may think you're accepting primitive types, but Java generics can use only reference types. Your values are being boxed when passed into this method. You could pass a String in as val.
That should indicate why 0 can't be converted to AnyNumType -- AnyNumType can be any reference type.
The best way to accept any primitive type is to have overloads for every primitive type, like many methods in the core library do. You can return the equivalent of 0 in each overload, e.g.
byte cancelAdd(byte val, String point)
{
if (checkModuleMatchAndOff(point) == true) return (byte) 0;
else return val;
}
The overloads for the other primitive types will look very similar.
You could change your method type to:
<AnyNumType extends Number> AnyNumType cancelAdd(AnyNumType val, String point);
I don't know exactly what you want do do inside the method, but this should allow you to pass in primitives via auto-boxing.
But it is not generally possible to use generics for primitive types in Java, autoboxing is, I think, the only way.
Returning a value other than the object you got in is possible, but you'd need some ugly reflection and casts, unfortunately. And it would not support all possible types.
(Maybe there is some library for this somewhere?)
For any doubters out there, here's sample code fresh out of Eclipse, without compilation errors, that demonstrates this:
public class NumberGenerix {
#SuppressWarnings("unchecked")
public static <Any extends Number> Any f(Any x) {
Class<?> k = x.getClass();
if (k == Integer.class) {
return (Any) Integer.valueOf(0);
} else if (k == Double.class) {
return (Any) Double.valueOf(0.0);
} else if (k == Long.class) {
return (Any) Long.valueOf(0L);
} else {
// and so on.
throw new RuntimeException("unsupported number type: " + k);
}
}
public static void main(String...args) {
Integer a = f(42);
System.out.println("a == " + a);
Long b = f(42L);
System.out.println("b == " + b);
Double c = f(42.0);
System.out.println("c == " + c);
}
}
We have Integer class in JAVA, but I couldn't find any equivalent class in C#? Does c# have any equivalent? If not, how do I get JAVA Integer class behavior in c#?
Why do I need this?
It is because I'm trying to migrate JAVA code to c# code. If there is an equivalent way, then code migration would be easier. To addon, I need to store references of the Integer and I don't think I can create reference of int or Int32.
C# has a unified type system, so int can be implicitly boxed into an object reference. The only reason Integer exists in Java is so that it can be converted to an object reference and stored in references to be used in other container classes.
Since C# can do that without another type, there's no corresponding class to Integer.
Code migration won´t work out of the box for any type of language without any manual changes. There are things such as a class Integer that simply does not exist within (C# why should it anyway, see recursives answer), so you´d have to do some work on your own. The nearest equivalent to what you´re after is Int32 or its alias int. However you may of course write your own wrapper-class:
public class Integer
{
public int Value { get; set; }
public Integer() { }
public Integer( int value ) { Value = value; }
// Custom cast from "int":
public static implicit operator Integer( Int32 x ) { return new Integer( x ); }
// Custom cast to "int":
public static implicit operator Int32( Integer x ) { return x.Value; }
public override string ToString()
{
return string.Format( "Integer({0})", Value );
}
}
The beauty of C# is that it has a unified type system. Everything derives from object, even primitive types. Because of this, all keywords are simply aliases for a corresponding class or struct. Java does not use a unified type system, so a separate Integer class is required to wrap the int primitive. In C# int is synonym for the Int32 struct.
What you're looking for has been right in front of you the whole time. Start using the dot notation directly on the int keyword (i.e. int.whatever()) to access the all goodness of the .NET version of the Javian Integer class.
I did some testing with Nullable types in a console application and it appears that they do not behave as you wish. For example:
static void Main(string[] args)
{
int? x = 1;
Foo(ref x);
Console.WriteLine(x);//Writes 2
}
private static void Foo(ref int? y)
{
y += 1;
var l = new List<int?>();
l.Add(y);
l[0] += 1;//This does not affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 2
Foo2(l);
}
private static void Foo2(List<int?> l)
{
l[0] += 1;
Console.WriteLine(l[0]);//writes 4
}
But if you roll your own generic class to wrap primitive/value types for use within your application you can get the behavior you are expecting:
public class MyType<T>
{
public T Value { get; set; }
public MyType() : this(default(T))
{}
public MyType(T val)
{
Value = val;
}
public override string ToString()
{
return this.Value.ToString();
}
}
static void Main(string[] args)
{
var x = new MyType<int>(1);
Foo(x);
Console.WriteLine(x);//Writes 4
}
private static void Foo(MyType<int> y)
{
y.Value += 1;
var l = new List<MyType<int>>();
l.Add(y);
l[0].Value += 1;//This does affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 3
Foo2(l);
}
private static void Foo2(List<MyType<int>> l)
{
l[0].Value += 1;
Console.WriteLine(l[0]);//writes 4
}
int, int? and System.Int32 are all struct and thus value types and does not compare to Java's Integer wrapper class which is a reference type.
System.Object class though a reference type can cause issue as boxing creates immutable object. In short, you can't alter a boxed value.
int a = 20;
Object objA = a; //Boxes a value type into a reference type, objA now points to boxed [20]
Object objB = objA; //Both objA & objB points to boxed [20]
objA = 40; //While objB points to boxed [20], objA points to a new boxed [40]
//Thus, it creates another ref type boxing a 40 value integer value type,
//Boxed values are immutable like string and above code does not alter value of previous boxed value [20]
Console.WriteLine($"objA = {objA}, objB={objB}");
//Output: objA = 40, objB=20
What exactly corresponds to Java's Integer is a custom generic wrapper class.
int a = 20;
Wrapper<int> wrapA = new Wrapper<int>(a);
Wrapper<int> wrapB = wrapA; //both wrapA and wrapB are pointing to [20]
wrapA.Value = 40; //Changing actual value which both wrapA and wrapB are pointing to
Console.WriteLine($"wrapA = {wrapA}, wrapB={wrapB}");
//Output: wrapA = 40, wrapB=40
Console.ReadKey();
Implementation of the wrapper class is given below:
public class Wrapper<T> where T : struct
{
public static implicit operator T(Wrapper<T> w)
{
return w.Value;
}
public Wrapper(T t)
{
_t = t;
}
public T Value
{
get
{
return _t;
}
set
{
_t = value;
}
}
public override string ToString()
{
return _t.ToString();
}
private T _t;
}
As pointed out in other answers, C# has a unified type system so everything derives from object. If you need to handle null values then use int? to specify that the integer object can be null.
c# have a integer type called int link is here
https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx
I have a rather simple test case below. I can send nulls to the constructor with no problems or errors, but when I try to send nulls to a method, it errors out with: error: incompatible types: <null> cannot be converted to int (or whatever type is expected). I'm not exactly sure why this occurs and I've seen in many places where sending nulls is acceptable practice. In all reality I just need nulls so that I can pump this example into Soot and Spark for static analysis, so the actual parameters sent to the methods are irrelevant other than a semantic necessity for entry points in the Spark-static analysis.
public class Test {
public Test(Object var1, Object var2) {
//do irrelevant stuff here with var1 and var2
}
public void api1(int x, int y) {
// do irrelevant stuff with x and y
}
public List<String> api2(String x, int y, boolean a) {
// do irrelevant stuff with x, y, and a and return a new ArrayList<String>()
}
}
public class Main {
public static void main(String[] args) {
Test usingVars = new Test(1, 2); // works, compiles and no errors
Test usingNulls = new Test(null, null); // works, compiles and no errors
/**
* usingVars will obviously work and not complain at all
*/
usingVars.api1(1, 2); // works, compiles and no errors
usingVars.api2("test", 1, false); // works, compiles and no errors
/**
* usingNulls should work, but throws this error on compilation:
* error: incompatible types: <null> cannot be converted to int
*/
usingNulls.api1(null, null); // should work, doesn't compile errors out
usingNulls.api2(null, null, null); // should work, doesn't compile errors out
}
}
primitives, (e.g., ints), can't take nulls. If you absolutely positively have to use a null value, you should define your method parameters as the appropriate wrapper class (e.g., java.lang.Integer for int):
public Test(Integer var1, Integer var2) {
//do irrelevant stuff here with var1 and var2
}
public void api1(Integer x, Integer y) {
// do irrelevant stuff with x and y
}
public List<String> api2(String x, Integer y, Boolean a) {
// do irrelevant stuff with x, y, and a and return a new ArrayList<String>()
}
In Java you have two types of variables, primitives and references.
A reference can be null as it references nothing. A primitive, such as int cannot be null, it has to be a number.
If you don't care what the values is you can use 0, -1 or Integer.MIN_VALUE
It is impossible to pass null to a method, constructor or otherwise, to a primitive type (e.g. int, short, byte, float) because in java you have two type systems, primitives and objects. Primitives can be cast to their object wrappers (e.g. Integer, Short, Byte, Float) and be used as objects, so if you need to pass null, use Integer, not int. However the convention in java for passing useless values for ints is to use -1.
In C# I can create my own implicit conversion for my classes as follows...
public static implicit operator TypeYouWantToChangeTo (ClassYouAreChanging c)
{
TypeYouWantToChangeTo x;
//convert c to x
return x;
}
How do you make a class be able to implicitly convert to another class? Also in C# I can change implicit to explicit to also create the ability to cast manually. How do you accomplish this in Java?
You can not overload operators with Java.
Add a method to your class of choice to perform the conversion.
For example:
public class Blammy
{
public static final Blammy blammyFromHooty(final Hooty hoot)
{
Blammy returnValue;
// convert from Hooty to Blammy.
return returnValue;
}
}
Edit
Only built-in types have implicit conversions.
Explicit conversion (in java) is called a cast. for example, int q = 15; double x = (double) q;
There can never be implicit conversions of your custom types.
extends and implements are not conversion.
All implicit conversions are for primitive types.
How can I check to make sure my variable is an int, array, double, etc...?
Edit: For example, how can I check that a variable is an array? Is there some function to do this?
Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).
The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:
int x;
You can be sure it will only ever hold int values.
If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.
If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:
List y;
...
if (y instanceof ArrayList) {
...its and ArrayList...
}
However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.
Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.
Example:
class Typetester {
void printType(byte x) {
System.out.println(x + " is an byte");
}
void printType(int x) {
System.out.println(x + " is an int");
}
void printType(float x) {
System.out.println(x + " is an float");
}
void printType(double x) {
System.out.println(x + " is an double");
}
void printType(char x) {
System.out.println(x + " is an char");
}
}
then:
Typetester t = new Typetester();
t.printType( yourVariable );
a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.
boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class.
Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.
I took this information from:
How do you know a variable type in java?
This can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.
By the way, this is known as Reflection. Here's some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/
Just use:
.getClass().getSimpleName();
Example:
StringBuilder randSB = new StringBuilder("just a String");
System.out.println(randSB.getClass().getSimpleName());
Output:
StringBuilder
You may work with Integer instead of int, Double instead of double, etc. (such classes exists for all primitive types).
Then you may use the operator instanceof, like if(var instanceof Integer){...}
Well, I think checking the type of variable can be done this way.
public <T extends Object> void checkType(T object) {
if (object instanceof Integer)
System.out.println("Integer ");
else if(object instanceof Double)
System.out.println("Double ");
else if(object instanceof Float)
System.out.println("Float : ");
else if(object instanceof List)
System.out.println("List! ");
else if(object instanceof Set)
System.out.println("Set! ");
}
This way you need not have multiple overloaded methods. I think it is good practice to use collections over arrays due to the added benefits. Having said that, I do not know how to check for an array type. Maybe someone can improve this solution. Hope this helps!
P.S Yes, I know that this doesn't check for primitives as well.
The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.
Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case object.getClass().isArray() will tell you.
I did it using: if(x.getClass() == MyClass.class){...}
I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.
//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);
// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);
// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);
Here is a method:
public static void checkClass (Object obj) {
Class cls = obj.getClass();
System.out.println("The type of the object is: " + cls.getSimpleName());
}
Basically , For example :
public class Kerem
{
public static void main(String[] args)
{
short x = 10;
short y = 3;
Object o = y;
System.out.println(o.getClass()); // java.lang.Short
}
}
None of these answers work if the variable is an uninitialized generic type
And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:
<T> T MyMethod(...){ if(T.class == MyClass.class){...}}
Is NOT valid because you cannot pull the type out of the T parameter directly, since it is erased at runtime time.
<T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}
This works because the caller is responsible to instantiating the variable out before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this
I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T is a kind of variable), I feel it should be included
var.getClass().getSimpleName()
Let's take a example
String[] anArrayOfStrings = { "Agra", "Mysore", "Chandigarh", "Bhopal" };
List<String> strList = Arrays.asList(anArrayOfStrings);
anArrayOfStrings.getClass().getSimpleName() //res => String[]
strList.getClass().getSimpleName() // res => ArrayList
You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.
reference - Here is the Oracle docs link
I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.
public class TypeTester <T extends Number>{
<T extends Object> String tester(T ToTest){
if (ToTest instanceof Integer) return ("Integer");
else if(ToTest instanceof Double) return ("Double");
else if(ToTest instanceof Float) return ("Float");
else if(ToTest instanceof String) return ("String");
else if(ToTest.getClass().isArray()) return ("Array");
else return ("Unsure");
}
}
I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.
public class Generics {
public static void main(String[] args) {
int [] myArray = new int [10];
TypeTester<Integer> callFunction = new TypeTester<Integer>();
System.out.println(callFunction.tester(myArray));
}
}
You can swap out the myArray in the final line for say 10.2F to test Float etc
public static void chkType(Object var){
String type = var.getClass().toString();
System.out.println(type.substring(16));
//assertEquals(type,"class java.lang.Boolean");
//assertEquals(type,"class java.lang.Character");
//assertEquals(type,"class java.lang.Integer");
//assertEquals(type,"class java.lang.Double");
}
A simple solution I found was the following rather than wondering about fire command. Also, you can check this article
public class DataTypeCheck
{
public static void main(String[] args)
{
String jobTitle = "Agent";
int employeeId = 7;
double floating= 10.0;
String bond = jobTitle + employeeId;
System.out.println(((Object)floating).getClass().getSimpleName());
System.out.println(((Object)employeeId).getClass().getSimpleName());
System.out.println(((Object)jobTitle).getClass().getSimpleName());
System.out.println(((Object)bond).getClass().getSimpleName());
}
}
Output:
Double
Integer
String
String