Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object to int: a better way? [closed]

Tags:

java

generics

I have a TreeSet, which will be full of integers. To make a long story short, I'm trying to loop starting after the last (greatest) value stored in the list. What I'm doing now to get the starting variable is:

    Object lastObj = primes.last();
    Integer last = new Integer(lastObj.toString());
    int start = 1 + last.intValue(); // the added 1 is just for program logic

I'm sure that there must be a better way to cast an object (which I know will always be an int) into the int 'start'. Anyone know of a better way of doing this?

like image 915
Jeremy Avatar asked May 20 '09 20:05

Jeremy


People also ask

Can we convert Object to Integer in java?

If your object is a String , then you can use the Integer. valueOf() method to convert it into a simple int : int i = Integer. valueOf((String) object);

How do you make an int long?

There are basically three methods to convert long to int: By type-casting. Using toIntExact() method. Using intValue() method of the Long wrapper class.

How do you turn an Object into a string?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


1 Answers

Are you using Java version 1.6? In that case you can take advantage of autoboxing and generics to clean up the code.

First, the TreeSet can be declared as containing only Integer objects

TreeSet<Integer> primes;

Now to get the object from the set you can

Integer last = primes.last();

and using the autoboxing feature you get

int start = 1 + last;
like image 188
Vincent Ramdhanie Avatar answered Oct 25 '22 19:10

Vincent Ramdhanie