Results 1 to 2 of 2
- 08-13-2009, 03:19 AM #1
Member
- Join Date
- Aug 2009
- Posts
- 3
- Rep Power
- 0
Need help using the Linked List class
I'm trying to insert entries in and get entries from a linked list Java LinkedList class. I want to create a linked list of arrays, but I'm starting with a linked list of integers to keep thinks simple. I can use <list>.add() to add an entry to the linked list but when I use <list>.get(<index>) to get the integer, the compiler gives the message
lltest.java:16: incompatible types
found : java.lang.Object
required: int
myInt = list.get(0);
I notice that
System.out.println("list " + list.get(0));
Will actually cause the integer to be displayed
Here is the code that I'm working with
import java.util.LinkedList;
public class lltest {
public static void main(String[] args) {
int myInt = 5;
LinkedList list = new LinkedList();
list.add(myInt);
myInt = 3;
System.out.println("list " + myInt);
myInt = list.get(0);
System.out.println("list " + myInt);
}
}
The full text when compiling is
lltest.java:13: warning: [unchecked] unchecked call to add(E) as a member of the
raw type java.util.LinkedList
list.add(myInt);
^
lltest.java:16: incompatible types
found : java.lang.Object
required: int
myInt = list.get(0);
^
1 error
1 warning
Can anyone help me understand how to add entries to and get entries from a LinkedList?
-
Your LinkedList is not a generic LinkedList and has no knowledge of what type of object it holds, only that it holds an object. When you extract the object by calling get(), all Java knows is that an Object has been returned, not an Integer object.
Your choices are to either cast the returned object as an Integer, and then call intValue() on the Integer object to get the int or else use a generic LinkedList<Integer>. This latter approach will allow the LinkedList to know that it holds Integer and only Integer objects and will only return Integer objects.
Similar Threads
-
Linked list
By rosh72851 in forum New To JavaReplies: 1Last Post: 02-05-2009, 07:21 AM -
Linked List integer list
By igniteflow in forum Advanced JavaReplies: 1Last Post: 12-10-2008, 08:53 PM -
Linked List help
By neobie in forum New To JavaReplies: 8Last Post: 12-22-2007, 03:15 AM -
Linked List
By rnavarro9 in forum New To JavaReplies: 0Last Post: 11-29-2007, 03:42 AM -
Help with linked list
By trill in forum New To JavaReplies: 1Last Post: 08-07-2007, 07:29 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks