Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: LinkedList Objects

  1. #1
    Junior Member
    Join Date
    Sep 2010
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default LinkedList Objects

    Hi all, I'm creating a LinkedList...I've removed most unnecessary code for simplicity. Here's what I expect to happen. I create a list opject, populate it with an item, get the size (which is 1) the I create a list2 object, populate it with an item and get the size of list again...which I would still expect to be 1, but it is 2...why is that happening? Here is my full code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner; //Needed for scanner class
     
    /**
     * class TestLinkedList -
     */
    public class TestLinkedList {
    	public static void main(String[] args) throws FileNotFoundException{
    		//Populate list with elements
    		IntLinkedList list = new IntLinkedList();
    //		list = getListFrom("project2.txt");
    		//Display original list
    list.addAfter(4);
    		System.out.println( "The original list size is: " + list.size() + 
    		" and contains the elements:");
    //		displayList( list );	
    		System.out.println();
    		//Sort list
    //		list = sortList( list ); 
    		//Display the sorted list
    IntLinkedList list2 = new IntLinkedList();
    list2.addAfter(5);
    		System.out.println( "The final list size is: " + list.size() + 
    		" and contains the sorted elements:");
    //		displayList( list );			
            System.exit(0);	//End Program
    	}//end method main
    }
     
    /**
     * class IntLinkedList -
     */
    class IntLinkedList{
        private static int     size; //the number of elements in the list
        private static IntNode head;
        private static IntNode tail;
        private static IntNode cursor;
        private static IntNode precursor;
        //
        //IntLinkedList
        //
        public IntLinkedList(){
        }//end IntLinkedList
        //
        //compute the number of nodes
        //
        public static int size(){
        	size = 0;
        	for ( cursor = head; cursor != null; cursor = cursor.getLink() ){
        		  size++;
        	}
        	return size;
        }//end size
        //
        //addAfter
        //
    	public static void addAfter( int value ){
            if ( cursor == null ) {  // either no current element or current element is first  
                // add element to the head of the list
                head = new IntNode( value, head );
                cursor = head;
             } else {               // cursor points to the middle of the list
            	cursor.setLink( new IntNode( value, cursor.getLink()) );
                //cursor = precursor.getLink();
             }
             if ( size() == 0 )     // the list was empty and tail needs to be initialized
                tail = head;
    	}
    }
     
    /**
     * class IntNode -
     */
    class IntNode{
    	//
    	//Variables
    	//
    	private int data; //variable to store an integer value.
    	private IntNode link; //variable to store an IntNode object.
    	//
    	//Non-default constructor to initialize the data fields
    	//
    	public IntNode( int initData, IntNode initLink ){
    		data = initData;
    		link  = initLink;
    	}
    	//
    	//Accessor and mutator methods for data and link fields
    	//
    	public int getData(){
    		return data;
    	}
    	public IntNode getLink(){
    		return link;
    	}
    	public void setData(int newData){
    		data = newData;
    	}
    	public void setLink(IntNode newLink){
    		link = newLink;
    	}
    }//end class IntNode

    Thanks for any help,
    Mason
    Last edited by copeg; October 13th, 2010 at 09:16 AM. Reason: Code Tags


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: LinkedList Objects

    All of your LinkedList variables are not instance variables, but rather class variables. eg static - when you set their value you end up changing the value for the class and not the instance. See Understanding Instance and Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

  3. #3
    Junior Member
    Join Date
    Sep 2010
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: LinkedList Objects

    OK, so if I declare the instance variable as:
    IntLinkedList list;

    How do I, for example, get the size as the project constraint for the size method is:
    public int size(){
    }//end size

    Thanks again.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: LinkedList Objects

    OK, so if I declare the instance variable as:
    IntLinkedList list;
    The variables of type IntLinkedList are not the problem, the problem is with the variables within that class and how they are declared (eg static).

    How do I, for example, get the size as the project constraint for the size method is:
    public int size(){
    }//end size
    You already have this method so I'm not sure what you are asking. Right now, size is static (and so are the other variables) so the method size() - in layman's terms - gets the size of ALL instances of said class. If you want it to retrieve only the size of the particular instance, see me post above

  5. #5
    Junior Member
    Join Date
    Sep 2010
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: LinkedList Objects

    OK, I see that when I use the word static, the method becomes part of the class and is not independent objects. But when I remove static, I get a null pointer exception...why did that happen? Here is the complete updated code, Ignore most of it, just look at list population portion.
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner; //Needed for scanner class
     
    /**
     * class TestLinkedList -
     */
    public class TestLinkedList {
        //
        public static void main(String[] args) throws FileNotFoundException{
          //
          IntLinkedList list = getListFrom("project2.txt");
          System.out.println( "The original list is:" );
          System.out.println();
          //displayList( list );
    //      list = sortList( list );
          System.out.println( list.size() );
     
          IntLinkedList list2 = null;
          list2.addAfter(2);
          System.out.println( list2.size() );
     
          System.out.println();
          System.out.println( "The final list is:" );
          System.out.println();
          //displayList( list );
        }//end main
        //
    	//
    	// getListFrom() method populates the linked list with elements
    	//	
    	private static IntLinkedList getListFrom(String path) throws FileNotFoundException{
    		//Get file
    		File file = new File(path);
    		Scanner inputFile = new Scanner(file);
    		IntLinkedList linkedList = null;
    		//Add elements
    		while (inputFile.hasNext()){
    			linkedList.addAfter(Integer.parseInt(inputFile.nextLine()));
    		}
    		inputFile.close();
    		return linkedList;
    	}//end method getListFrom
    	//
    	// displayList() method prints the elements of the linked list
    	//
    //	private void displayList( IntLinkedList list ){
    //		IntLinkedList.printList();
    //		System.out.println();
    //		System.out.println(IntLinkedList.size());
    //	}//end displayList
        //
    //    private static IntLinkedList mergeSortedLists(
    //      IntLinkedList first,
    //      IntLinkedList second
    //    ){
    //    }//end mergeSortedLists
        //
    //    private static IntLinkedList sortList( IntLinkedList list ){
    //    }//end sortList
        //
      }//end class TestIntLInkedList
     
     
     
     
     
     
     
    /**
     * class IntLinkedList -
     */
    class IntLinkedList{
        private int     size; //the number of elements in the list
        private IntNode head;
        private IntNode tail;
        private IntNode cursor;
        private IntNode precursor;
        //
        //IntLinkedList
        //
        public IntLinkedList(){
        	head=null;
        }//end IntLinkedList
        //
        //compute the number of nodes
        //
        public int size(){
        	size = 0;
        	for ( cursor = head; cursor != null; cursor = cursor.getLink() ){
        		  size++;
        	}
        	return size;
        }//end size
        //
        //addAfter
        //
    	public void addAfter( int value ){
            if ( cursor == null ) {  // either no current element or current element is first  
                // add element to the head of the list
                head = new IntNode( value, head );
                cursor = head;
             } else {               // cursor points to the middle of the list
            	cursor.setLink( new IntNode( value, cursor.getLink()) );
                //cursor = precursor.getLink();
             }
             if ( size() == 0 )     // the list was empty and tail needs to be initialized
                tail = head;
    	}
    	//
        //Prints list elements
    	//
        public void printList() {
        	IntNode curr = head;
            while (curr != null) {
                System.out.print(curr.getData() + " ");
                curr = curr.getLink();
            }
        }
    }
     
     
     
     
     
     
     
    /**
     * class IntNode -
     */
    class IntNode{
    	//
    	//Variables
    	//
    	private int data; //variable to store an integer value.
    	private IntNode link; //variable to store an IntNode object.
    	//
    	//Non-default constructor to initialize the data fields
    	//
    	public IntNode( int initData, IntNode initLink ){
    		data = initData;
    		link  = initLink;
    	}
    	//
    	//Accessor and mutator methods for data and link fields
    	//
    	public int getData(){
    		return data;
    	}
    	public IntNode getLink(){
    		return link;
    	}
    	public void setData(int newData){
    		data = newData;
    	}
    	public void setLink(IntNode newLink){
    		link = newLink;
    	}
    }//end class IntNode
    Last edited by copeg; October 13th, 2010 at 12:56 PM. Reason: Code Tags

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: LinkedList Objects

    I have edited your post, but for future reference please surround your code with the
    [highlight=java] [/highlight]
    tags, without which your code is completely illegible.

    Where is the exception thrown? Exceptions give line values and are essential in debugging. Please post the full exception message.

  7. #7
    Junior Member
    Join Date
    Sep 2010
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: LinkedList Objects

    Sorry about the TAGS, don't know how to do that. When run, Eclipse:
    Exception in thread "main" java.lang.NullPointerException
    at TestLinkedList.getListFrom(TestLinkedList.java:39)
    at TestLinkedList.main(TestLinkedList.java:12)

    When everything is static it works???

  8. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: LinkedList Objects

    The linkedList in the references method is never instantiated.
    IntLinkedList linkedList = null;
    linkedList.add(1);//throws null pointer exception

    You must instantiate the object before using its instance variables/methods.
    IntLinkedList linkedList = new IntLinkedList();

  9. #9
    Junior Member
    Join Date
    Sep 2010
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs down Re: LinkedList Objects

    Thank you so much! I'm on the right track now...man...Thank you! Ignore the code below, just wanted to put a tag around it. Again...thank you.

    import java.io.*;
    import java.util.*;
    public class TestLinkedList {
        //
        public static void main(String[] args) {
          //
          IntLinkedList list = getListFrom( "A:/Project3.txt" );
          System.out.println( "The original list is:" );
          System.out.println();
          displayList( list );
          list = sortList( list );
          System.out.println();
          System.out.println( "The final list is:" );
          System.out.println();
          displayList( list );
          //
        }//end main
        //
        private static IntLinkedList getListFrom( String path ) {
        }//end getLinkedList
        //
        private static void displayList( IntLinkedList list ){
        }//end displayList
        //
        private static IntLinkedList mergeSortedLists(
          IntLinkedList first,
          IntLinkedList second
        ){
        }//end mergeSortedLists
        //
        private static IntLinkedList sortList( IntLinkedList list ){
        }//end sortList
        //
      }//end class TestIntLInkedList

  10. #10
    Junior Member
    Join Date
    Sep 2010
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: LinkedList Objects

    I used the # tag for code...what do you use for java to get the color?

  11. #11
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: LinkedList Objects

    Quote Originally Posted by thedolphin13 View Post
    I used the # tag for code...what do you use for java to get the color?
    PHP Code:
    [highlight=java]place code here[/highlight

  12. #12
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: LinkedList Objects

    Quote Originally Posted by thedolphin13 View Post
    I used the # tag for code...what do you use for java to get the color?
    To use java tags:
    [highlight=java] and [/highlight]
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Help with background and objects
    By Afromiffo in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 8th, 2010, 01:19 AM
  2. Objects
    By chronoz13 in forum Java Theory & Questions
    Replies: 5
    Last Post: January 20th, 2010, 12:50 PM
  3. Writing clone() method for LinkedList
    By vluong in forum Collections and Generics
    Replies: 6
    Last Post: October 27th, 2009, 08:41 AM
  4. Arrays Of Objects?
    By MysticDeath in forum Object Oriented Programming
    Replies: 2
    Last Post: October 20th, 2009, 09:39 PM
  5. Implementing LinkedList as a user?
    By vluong in forum Collections and Generics
    Replies: 3
    Last Post: October 15th, 2009, 03:00 AM