Programing

Java에서 int에서 Long으로 어떻게 변환합니까?

lottogame 2020. 5. 5. 19:29
반응형

Java에서 int에서 Long으로 어떻게 변환합니까?


여기에 모두를 찾아 계속 구글 사람들로부터가는 문제 필요 longint하지 다른 방법으로 주위를. 그러나 나는 확실히 내가로부터 가기 전에이 시나리오에 실행 된 유일한 사람이 아니에요 야 int에가 Long.

내가 찾은 유일한 다른 답변은 "처음에는 길게 설정했다"는 것인데 실제로 질문을 다루지 않습니다.

처음에 캐스팅을 시도했지만 " 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);
}

내가 조금 당황했다고 상상할 수 있듯이 int일부 콘텐츠가 들어 오고이 ArrayList정보를 저장하는 엔티티에는 시퀀스 번호가 Long이기 때문에 사용이 중단되었습니다.


캐스트 long캐스트 사이에는 차이 Long있습니다. long(원시 값)으로 캐스트하면 자동으로 (포장 Long하는 참조 유형) 상자로 채워 져야합니다 .

또는 new의 인스턴스를 생성 Long하여 int값으로 초기화하는 사용할 수도 있습니다 .


다음을 사용하십시오 Long.valueOf(int);..


정수를 정수로 입력 한 경우 다음을 수행 할 수 있습니다.

Integer y = 1;
long x = y.longValue();

사용하다

new Long(your_integer);

또는

Long.valueOf(your_integer);

나는이 작은 장난감을 가지고 있으며 일반 인터페이스가 아닌 인터페이스도 처리합니다. 피드가 잘못되면 ClassCastException이 발생해도 괜찮습니다 (OK and happy)

public class TypeUtil {
    public static long castToLong(Object o) {
        Number n = (Number) o;
        return n.longValue();
    }
}

Java에서는 다음을 수행 할 수 있습니다.

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

귀하의 경우에는 다음과 같습니다.

content.setSequence(new Long(i));

어떻게

int myInt = 88;

// 컴파일하지 않습니다

Long myLong = myInt;

// Compiles, and retains the non-NULL spirit of int. The best cast is no cast at all. Of course, your use case may require Long and possible NULL values. But if the int, or other longs are your only input, and your method can be modified, I would suggest this approach.

long myLong = myInt;

// Compiles, is the most efficient way, and makes it clear that the source value, is and will never be NULL.

Long myLong = (long) myInt;

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

}

 1,new Long(intValue);
 2,Long.valueOf(intValue);

I had a great deal of trouble with this. I just wanted to:

thisBill.IntervalCount = jPaidCountSpinner.getValue();

Where IntervalCount is a Long, and the JSpinner was set to return a Long. Eventually I had to write this function:

    public static final Long getLong(Object obj) throws IllegalArgumentException {
    Long rv;

    if((obj.getClass() == Integer.class) || (obj.getClass() == Long.class) || (obj.getClass() == Double.class)) {
        rv = Long.parseLong(obj.toString());
    }
    else if((obj.getClass() == int.class) || (obj.getClass() == long.class) || (obj.getClass() == double.class)) {
        rv = (Long) obj;
    }
    else if(obj.getClass() == String.class) {
        rv = Long.parseLong(obj.toString());
    }
    else {
        throw new IllegalArgumentException("getLong: type " + obj.getClass() + " = \"" + obj.toString() + "\" unaccounted for");
    }

    return rv;
}

which seems to do the trick. No amount of simple casting, none of the above solutions worked for me. Very frustrating.


 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)

As soon as there is only method Long.valueOf(long), cast from int to long will be done implicitly in case of using Long.valueOf(intValue).

The more clear way to do this is

Integer.valueOf(intValue).longValue()

참고URL : https://stackoverflow.com/questions/1302605/how-do-i-convert-from-int-to-long-in-java

반응형