Results 1 to 4 of 4
  1. #1
    aldz24 is offline Member
    Join Date
    Aug 2016
    Posts
    21
    Rep Power
    0

    Default Converting an Arraylist Code to a LinkedList to store,initialize

    Hi There !

    I am currently working on a code that implements a LinkedList that reads from an input file.The code I have right now uses an Arraylist but I want ti use LinkedList instead. I already have a set LinkedList java class and a Node Java Class in a separate program.
    My inputfile:



    Here is my code that I want to replace with a LinkedList:
    Java Code:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    public class TestingCode {
    /**
    * The main method starts the program
    *
    *@param args is the input file
       */
    
       public static void main(String[] args) {
       //error checking for commandline input
          if(args.length != 1){
             System.out.println("Please enter at least one input file into the argument.");
             //terminates the program if more than 1 is entered
             System.exit(1);
          }
       
       
          String csvFile = args[0];
          String line = "";
          String cvsSplitBy = ",";
       
          List<HawaiiNativeForestBirds>  listofBirds = new ArrayList<HawaiiNativeForestBirds>();
          try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
          
             while ((line = br.readLine()) != null) {
             
                // use comma as separator
                String[] bird = line.split(cvsSplitBy);
                HawaiiNativeForestBirds Hawaiinbird= new HawaiiNativeForestBirds(bird[0],bird[1],bird[2],Integer.valueOf(bird[3]));
                listofBirds.add(Hawaiinbird);
             }
          
          } 
          catch (IOException e) {
             e.printStackTrace();
          }
       // First display null values
          HawaiiNativeForestBirds[]  hbirds=new        HawaiiNativeForestBirds[listofBirds.size()];
          System.out.println("index   " + "    element   ");  
          int i=0;
          for (HawaiiNativeForestBirds hbird:hbirds){
             i++;
             System.out.println(i+"            "+hbird);
          }
        // Now display actual values
          hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);
       
          System.out.println("index   " + "name   "+ "   Scientific Name     "+ "        Color     " +       "      Population");        
          i=0;
          for (HawaiiNativeForestBirds hbird:hbirds){
             i++;
             System.out.println(i+"   "+hbird.toString());
          }
       
       } // end of main 
    } //end of class 
    
    /**
       * Class HawaiianNativeForestBirds stores and displays the data for each HawaiianTheme object
       * 
       * 
       */
      
    
     
    class HawaiiNativeForestBirds {
       private String name;
       private String scientificname;
       private String color;
       private Integer population;
       public HawaiiNativeForestBirds(){
       
       }
       //constructor - used to initialize the four data fields
          /**
       * Stores the name,scientific name, color and population of the Hawaiian Birds
        *  
        * 
        * @param name is the name of the birds from the array list
        * @param scientificname is the scientific name of the birds in the array list
        * @param color is the color of each of the birds in the array list
        * @param population is the total number of birds in the array list   
        */
    
       public HawaiiNativeForestBirds(String name, String scientificname,
            String color, Integer population) {
          super();
          this.name = name;
          this.scientificname = scientificname;
          this.color = color;
          this.population = population;
       }  
    /**
        * Gets each bird's name
        * 
        * @return the birds name
        */
    
    
       public String getName() {
          return name;
       }
        /**
        * Sets each birds name
        * 
        * @param name is the bird's name
        */
    
       public void setName(String name) {
          this.name = name;
       }
       /**
        * Gets the bird's scientific name
        * 
        * @return the bird's scientific name
        */
    
       public String getScientificname() {
          return scientificname;
       }
        /**
        * Sets the birds scientific name
        * 
        * @param scientificname is the bird's scientific name
        */
    
       public void setScientificname(String scientificname) {
          this.scientificname = scientificname;
       }
       /**
        * Gets the bird's color
        * 
        * @return the bird's color
        */
    
       public String getColor() {
          return color;
       }
        /**
        * Sets the bird's color
        * 
        * @param color is the bird's color
        */
    
       public void setColor(String color) {
          this.color = color;
       }
       /**
        * Gets the bird's population
        * 
        * @return total population of the bird
        */
    
       public Integer getPopulation() {
          return population;
       }
        /**
        * Sets the bird's population
        * 
        * @param population is the total population of the bird
        */
    
       public void setPopulation(Integer population) {
          this.population = population;
       }
      /**
        * Display the output 
        * 
        * @return the name, scientificname, color, and population of the bird
        */
    
       public String toString() {
          String output = name +"     "+      scientificname + "             "+ color +"           "+        population;
          return output;
       }//end of toString 
               
    }// end of class
    As you can see, the code runs fine but what If I wanted to use Linked List instead?

    LinkedList Class
    Java Code:
    /**
     * A generic list of linked nodes
     * 
     * 
     */
    public class LinkedList<T> implements ListInterface<T> {
    
    	// reference to first node in the linked list (linked nodes)
       protected Node<T> head = null;
    	// Total number of items, which is used
    	// for error checking and node removal.
       protected Integer size = new Integer(0);
    
       public LinkedList() {
       	// no code, because data fields already initialized
       }
    
    	/**
    	 * Adds an item (of any class) to the end of the list
    	 * 
    	 * @param item
    	 *            is the object that is added to the list
    	 */
       public void add(T item) {
       	// case 1: if empty list
          if (head == null) {
          	// list is empty, so add to beginning of list
          	// make new node and assign to head of list
             head = new Node<T>(item, null);
          }
          // if not empty list
          else {
          	// case2: add to end of list
          	// current starts at 2nd node in list
             Node<T> previous = head;
             Node<T> current = head.getNext();
          	// while not at end of list
             while (current != null) {
             	// advance to next node
                previous = current;
                current = current.getNext();
             }
          	// Add new node to end of list:
          	// Make new node that has "null" for next.
          	// A node with "null" is always the last node
             Node<T> node = new Node<T>(item, null);
          	// Point previous node (last node) to new node
             previous.setNext(node);
          }
       	// increase size of list
          size++;
       }
    
    	/**
    	 * Gets an item (address to an item) from any position in the list.
    	 * 
    	 * @param position
    	 *            The position of an item in the list.
    	 * @returns the address to the requested item
    	 * @exception ListException
    	 *                if an item does not exist at that position
    	 */
       public T get(Integer position) throws ListException {
       	// check if empty list
          if (head == null) {
             throw new ListException("Cannot get an item from an empty list!");
          }
       	// if position is outside range, throw exception
          if (position < 1 || position > size) {
             throw new ListException(position + " is outside list range!");
          }
       	// Find node:
       	// counter to keep track of loops
          Integer counter = new Integer(1);
       	// point to current node
          Node<T> current = head;
          while (!counter.equals(position)) {
          	// BAD CODE: while(counter != position){
          	// goto next node for current pointer
             current = current.getNext();
          	// add 1 to counter
             counter++;
          }
       	// return the data (item) stored by the node
          return current.getData();
       }
    
    	/**
    	 * Removes an item at any position from the list.
    	 * 
    	 * @param position
    	 *            The position of an item in the list.
    	 * @exception ListException
    	 *                if an item does not exist at that position
    	 */
       public void remove(Integer position) throws ListException {
       	// check if empty list
          if (head == null) {
             throw new ListException("cannot remove from empty list");
          }
       	// if position is outside range, throw exception
          if (position < 1 || position > size) {
             throw new ListException(position + " is outside list range.");
          }
       	// if at beginning of list
          if (position.equals(1)) {
          	// remove 1st node
             head = head.getNext();
          }
          // if not at beginning of list
          else {
          	// Find node:
          	// point previous to 1st node
             Node<T> previous = head;
          	// point current to 2nd node
             Node<T> current = head.getNext();
          	// loop position-2 number of times
             for (int i = 2; i < position; i++) {
             	// goto next node for previous and current
                previous = current;
                current = current.getNext();
             }
          	// Point the previous node to node after current node.
          	// This "skips" over one node, thus removing it!
             previous.setNext(current.getNext());
          }
       	// decrease size of list
          size--;
       }
    
    	/**
    	 * Automatically called by println() or print()
    	 * 
    	 * @return a String of the List in CSV (comma separated values) format
    	 */
       public String toString() {
       	// instantiate empty string
          String csvFormat = new String("");
       	// display position of each item to user
          Integer position = new Integer(1);
       	// loop through all the nodes in linked list
          for (Node<T> current = head; current != null; current = current
          		.getNext()) {
          	// keep adding to end of string
             csvFormat = csvFormat + position + ", " + current.toString() + "\n";
          	// add one to position for each loop
             position++;
          }
          return csvFormat;
       }
    
    	/**
    	 * This Is An "Accessor" Method - Used To Get A Data Field.
    	 * 
    	 * @return the size of the list
    	 */
       public Integer getSize() {
          return size;
       }
    
    }// end of class
    Node Class
    Java Code:
    /**
     * A generic Node class that Stores a reference to Data and the next Node
     * 
     * 
     */
    public class Node<T> {
    
    	// data fields (reference variables)
    	// data stores an object of any class
       private T data;
    	// next points to the next node
       private Node<T> next;
    
    	/**
    	 * Constructor - Used To Create EAch Object & Initialize DAta Fields.
    	 * 
    	 * @param data2
    	 *            initializes the data reference variable.
    	 * @param next2
    	 *            initializes the next reference variable..
    	 */
       public Node(T data2, Node<T> next2) {
          data = data2;
          next = next2;
       }
    
    	/**
    	 * Used to Display The Data Stored In EAch Node.
    	 * 
    	 * @return a String for the data
    	 */
       public String toString() {
          return data.toString();
       }
    
    	/**
    	 * This Is An "Accessor" Method - Used To Get A Data Field.
    	 * 
    	 * @return the data
    	 */
       public T getData() {
          return data;
       }
    
    	/**
    	 * This Is An "Accessor" Method - Used To Get A Data Field.
    	 * 
    	 * @return the address to the next node
    	 */
       public Node<T> getNext() {
          return next;
       }
    
    	/**
    	 * This Is A "Mutator" Method - Used To Set A Data Field.
    	 * 
    	 * @param data2
    	 *            is a pointer to an object.
    	 */
       public void setData(T data2) {
          data = data2;
       }
    
    	/**
    	 * This Is A "Mutator" Method - Used To Set A Data Field.
    	 * 
    	 * @param next2
    	 *            is a pointer to the next node.
    	 */
       public void setNext(Node<T> next2) {
          next = next2;
       }
    
    
    } // end of class

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Converting an Arraylist Code to a LinkedList to store,initialize

    Unless you want to practice writing linked list code you can just import the java.util.LinkedList which also implements the same List interface
    that ArrayList implements. If you do want to write you own then just do so but implement the List interface. Then you should not have to
    modify your main code. As long as you conform to the List interface, the internals are up to you.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    aldz24 is offline Member
    Join Date
    Aug 2016
    Posts
    21
    Rep Power
    0

    Default Re: Converting an Arraylist Code to a LinkedList to store,initialize

    Quote Originally Posted by jim829 View Post
    Unless you want to practice writing linked list code you can just import the java.util.LinkedList which also implements the same List interface
    that ArrayList implements. If you do want to write you own then just do so but implement the List interface. Then you should not have to
    modify your main code. As long as you conform to the List interface, the internals are up to you.

    Regards,
    Jim
    How to I do the "Conforming" part of list interface?

    I tried the importing part and change arraylist to linkedlist and it does indeed work but what if I had to do it the way of the List Interface?

    Would the process be like the same but then i have to use add method and the getSize?

    Can you show me a format of it?
    Last edited by aldz24; 10-12-2016 at 11:10 PM.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Converting an Arraylist Code to a LinkedList to store,initialize

    When you implement the list interface you simply provide the code that does what the method says. For example,
    the ArrayList is backed by an array. So when you get an item, you are simply using the supplied index to get the item
    in the backed array. In a linked list implementation, it would be more difficult because you can't directly index a link in
    a linked list so you would have to traverse the list and count (from either one end or the other depending on which is
    more efficient). On the other hand, ArrayLists can't increase in size very elegantly nor can you efficiently delete an
    element from an array. So you have to do a lot of copying. But this is trivial for linked lists. That's why, depending
    on the requirements of your application one of the List implementations might be preferred over another.

    Since an ArrayList is easier to implement than a linked list, you might want to try creating your own ArrayList to get the
    "feel" for it. Then you can use what you learned and implement a linked list. Just remember that unlike arrays, an ArrayList
    implementation must grow dynamically. And its capacity to hold items is different than the number of items that are
    actually present (i.e. the size of the ArrayList).

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. differece between ArrayList and LinkedList
    By srinivasmallabathula in forum Advanced Java
    Replies: 3
    Last Post: 06-14-2011, 08:37 AM
  2. Replies: 2
    Last Post: 04-28-2011, 11:25 AM
  3. ArrayList vs LinkedList
    By rp181 in forum New To Java
    Replies: 2
    Last Post: 02-27-2011, 02:08 AM
  4. Replies: 16
    Last Post: 05-08-2008, 09:45 PM
  5. Replies: 0
    Last Post: 12-05-2007, 02:09 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •