jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes int to Integer object conversions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "int to Integer object conversions" Watch "int to Integer object conversions" New topic

int to Integer object conversions

Lionel Goodhart

Joined: Feb 29, 2004
Posts: 1
This method needs to go through an array and convert all of the integers in the array to Integer objects and store them in a linked list. This is what I have so far.
ListNode convert(int[] array)
int arrayPosition = 0;
Integer listnod = 0;
while (arrayPosition < arr.size()-1)
listnod = arr[arrayPos]; //Converted to object.
head = new ListNode(listnod, null) //Stored into node.
Im not sure if this code is correct, but I was wondering if anyone could help me out by giving me some correction or tips on how to optimize the code. Thanks in advance.
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Hello Lionel,
Welcome to JavaRanch.
You�ve got a couple of issues in your code fragment...
This line:

is incorrect. You cannot assign an int to an Integer object. You can construct an Integer object using an int value by using the constructor:

so I can do this:

So what you will want to do is iterate through your array, and for each element in the array, create an Integer object and add that object to your Linked List.
As for your iteration loop: you are initializing your loop counter arrayPosition to zero, but then comparing it to the array size in your loop test; it will immediately evaluate as false (unless our array size is zero) and your loop code will never run.
Also, in your while loop, even if you never increment the value of arrayPosition, so if you do enter your loop, it will be an endless loop.
Generally when you iterate through an array, you do so as follows

You can iterate through an array using a while loop, but usually you only do so when there are certain decisions for doing so.
So, iterate through your array, and then for each int in the array, create an Integer Object and then add it to the LinkedList. To add something to a LinkedList, you use the add(Object o) method:

You should be able to put these code fragments together to get the code that you need to do the task at hand.
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
I'd say you're almost there. (Though, I've never seen the ListNode class you speak of...did you write it yourself?)

I agree. Here's the link: http://aspose.com/file-tools
subject: int to Integer object conversions
It's not a secret anymore!