How do I convert from int to Long in Java?

2019-01-07 02:49发布

I keep finding both on here and Google people having troubles going from long to int and not the other way around. Yet I'm sure I'm not the only one that has run into this scenario before going from int to Long.

The only other answers I've found were "Just set it as Long in the first place" which really doesn't address the question.

Can someone help me out here? I initially tried casting but I get a "Cannot cast from int to Long"

for (int i = 0; i < myArrayList.size(); ++i ) {
    content = new Content();
    content.setDescription(myArrayList.get(i));
    content.setSequence((Long) i);
    session.save(content);
}

As you can imagine I'm a little perplexed, I'm stuck using int since some content is coming in as an ArrayList and the entity for which I'm storing this info requires the sequence number as a Long.

Thanks!

12条回答
混吃等死
2楼-- · 2019-01-07 03:18

Note that there is a difference between a cast to long and a cast to Long. If you cast to long (a primitive value) then it should be automatically boxed to a Long (the reference type that wraps it).

You could alternatively use new to create an instance of Long, initializing it with the int value.

查看更多
Root(大扎)
3楼-- · 2019-01-07 03:20

Use the following: Long.valueOf(int);.

查看更多
Anthone
4楼-- · 2019-01-07 03:20

use

new Long(your_integer);

or

Long.valueOf(your_integer);
查看更多
爷的心禁止访问
5楼-- · 2019-01-07 03:21

In Java you can do:

 int myInt=4;
 Long myLong= new Long(myInt);

in your case it would be:

content.setSequence(new Long(i));
查看更多
太酷不给撩
6楼-- · 2019-01-07 03:22
 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)
查看更多
萌系小妹纸
7楼-- · 2019-01-07 03:23

We shall get the long value by using Number reference.

public static long toLong(Number number){
    return number.longValue();
}

It works for all number types, here is a test:

public static void testToLong() throws Exception {
    assertEquals(0l, toLong(0));   // an int
    assertEquals(0l, toLong((short)0)); // a short
    assertEquals(0l, toLong(0l)); // a long
    assertEquals(0l, toLong((long) 0)); // another long
    assertEquals(0l, toLong(0.0f));  // a float
    assertEquals(0l, toLong(0.0));  // a double

}
查看更多
登录 后发表回答