Java object for int: best way?

I have a TreeSet that will be full of integers. In short, I am trying to start a loop after the last (largest) value stored in a list. Now I get the initial variable:

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

I am sure there should be a better way to throw an object (which I know will always be int) into int 'start'. Does anyone know a better way to do this?

+7
java generics
source share
6 answers

Are you using Java version 1.6? In this case, you can use autoboxing and generics to clear the code.

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

 TreeSet<Integer> primes; 

Now, to get an object from a set, you can

 Integer last = primes.last(); 

and using the autoboxing function, you get

 int start = 1 + last; 
+8
source share

In J2SE 5 or later, this happens automatically, with the "autoboxing" function.

 int start = 1 + last; 

http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

In addition, if you know that they will all be Integer objects, use a parameterized type:

 List<Integer> obj = new ArrayList<Integer>()... 

Then combine it with the auto-boxing feature:

 int start = 1 + obj.last(); 
+8
source share

If you know that they were "int" when they were inserted, then they were converted to Integer, whereas in collections (collections cannot contain primitives, only objects), as such, you can simply Integer last = (Integer)lastObj; .

Ideally, you would use a TreeSet<Integer> , and then it would just feed you integers.

+4
source share

If you know that primes contains only integers, you should make primes in TreeSet<Integer> .

Then it will be:

 int start = 1 + primes.last().intValue(); 

If you cannot use generics, use this:

 int start = 1 + ((Integer)prime.last()).intValue(); 

Casting in a string would be just plain stupid.

By the way, I do not suggest using autoboxing. He does everything behind your back. The explicit use of Integer seems clearer to me. But these are just my personal preferences, you can use autoboxing if you want.

+4
source share

To publish Java 1.4, you can use autoboxing .

So he becomes

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

If you used generics with your TreeSet ( TreeSet<Integer> ), you could remove the original cast in Integer.

+3
source share

Why can't you just use it and not convert it to a string and then parse that string and create a new link?

 Object lastObj = primes.last(); int start = 1 + ( ( Integer )lastObj ).intValue(); 
+2
source share

All Articles