File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int to Integer object conversions

 
Lionel Goodhart
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 624
IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 268
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd say you're almost there. (Though, I've never seen the ListNode class you speak of...did you write it yourself?)

sev
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic