简体   繁体   中英

Why I get a compiler error (cannot cast from long to Long) on a TimeUnit to a date, while if i change the java compiler i don't get it anymore

I have this code, and on the last line compiler gives me error: Cannot cast from long to Long. If i change my java compiler, i uncheck the checkbox "Use compliance from execution enviroment CDC-1.1/Foundation.1-1 on the java BUild path" and i select a compliance compiler level 1.7 I don't get the error anymore? And there is a way to don't get that error don't changing java compiler compliance?

package data;

import java.util.Date;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class DataProva {

    public static void main(String[] args) {


        Calendar cal1 = Calendar.getInstance(); 
        Calendar cal2 = Calendar.getInstance();  

        cal2.set(2010,0,1,12,0);

        Date date1 = cal2.getTime();

        System.out.println(date1);  

        long mill = Math.abs(cal1.getTimeInMillis() - date1.getTime());


        long hours = TimeUnit.MILLISECONDS.toHours(mill);


        Long dayss = TimeUnit.HOURS.toDays(hours); // here i get compiler error cannot cast from long to Long

Thank you so much!

EDIT: I changed long dayss to Long because java changed it. I have still 2 question: 1) Why my java use such old version to compile. 2) Why the if i cast it like this: Long dayss = (Long) TimeUnit.HOURS.toDays(hours); doesn't work the same. How can i build a wrapper then in java 1.4

Each project i do start like this: mypic

Java 1.5 adds a feature called auto-boxing, which implicitly converts between primitive types (like long ) and boxed wrapper types (like Long ).

Earlier versions do not have this feature, so you need to construct the wrapper types yourself.

if you want to continue to use Java 1.4 then replace this

Long dayss = TimeUnit.HOURS.toDays(hours); // here i get compiler error cannot cast from long to Long

to this

Long dayss = Long.valueOf(TimeUnit.HOURS.toDays(hours)); // here i get compiler error cannot cast from long to Long

Actually that is better coding practice no matter which version of java your using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM