• Post Reply Bookmark Topic Watch Topic
  • New Topic

convert primitive long to Long  RSS feed

 
yotam laor
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have this code which suppose to sort files by their length and return a string[] of th file names:


Now, in the following line: absoluteOrderFiles[absoluteIndex].length() < sizeOrderList.get(sizeIndex).length()
I need to use the compareTo which only exists in Long object.

How do I convert primitive long to Long?

and is it possible to do it in a single line?

Thanks!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just assign the value to the Long variable:

The value is automatically converted by autoboxing.
If you want to do it explicitly, use Long.valueOf(...):

But there's really no need to do this explicitly.
 
yotam laor
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I edited my question,

Hope now it is clear...
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you think you need to use Long.compareTo(...) instead of just comparing the values with "<"? What's wrong with comparing the values with "<"?

Instead of

you could write

but it would gain you absolutely nothing, you would just be making the code more complicated.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, there's no need to implement your own sorting algorithm (unless this is homework which explicitly requires that), you can use one of the sort(...) methods of class java.util.Arrays instead. Use the version that takes an array and a Comparator, and implement the Comparator to compare the file sizes.
 
yotam laor
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is school assginment, so I don't think anything

the instructions are "use .compareTo() method".

But if it makes things more complicated I'll just elegantly ignore them.

Thanks....
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Before Java5 you had to use different techniques because boxing and the valueOf method were not available.But that was ten years ago.

If you have been told to use compareTo, then you have to sue compareTo even though it appears to be complicated coding. This is obviously an assignment to explore the Comparable interface. Read that link and also this Java Tutorials section.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!