Making a list of objects of generic type.

0 Adam Garza · October 11, 2015
First time posting a question & not sure who to even direct to. Name is Adam & i'm new to Java. I have been asked to modify a given 'linked list' code to make it a list of generic type (each link object contains an object of generic type instead of a numeric value). I have to define a Person class which has lastName, firstName, & age to test is with. I will show you the given 'linked list' code first. Then I will show you my edited (none working) version. Remember, I'm still a spring chick regarding java, so any advise is greatly appreciated.  Thanks Adam 
---------------GIVEN LINKED LIST BELOW-------------------------------------

class Link
   {
   public int iData;              // data item (key)
   public double dData;           // data item
   public Link next;              // next link in list
// -------------------------------------------------------------
   public Link(int id, double dd) // constructor
      {
      iData = id;
      dData = dd;
      }
// -------------------------------------------------------------
   public void displayLink()      // display ourself
      {
      System.out.print("{" + iData + ", " + dData + "} ");
      }
   }  // end class Link
////////////////////////////////////////////////////////////////


class LinkList
   {
   private Link first;            // ref to first link on list

// -------------------------------------------------------------
   public LinkList()              // constructor
      {
      first = null;               // no links on list yet
      }
// -------------------------------------------------------------
   public void insertFirst(int id, double dd)
      {                           // make new link
      Link newLink = new Link(id, dd);
      newLink.next = first;       // it points to old first link
      first = newLink;            // now first points to this
      }
// -------------------------------------------------------------
   public Link find(int key)      // find link with given key
      {                           // (assumes non-empty list)
      Link current = first;              // start at 'first'
      while(current.iData != key)        // while no match,
         {
         if(current.next == null)        // if end of list,
            return null;                 // didn't find it
         else                            // not end of list,
            current = current.next;      // go to next link
         }
      return current;                    // found it
      }
// -------------------------------------------------------------
   public Link delete(int key)    // delete link with given key
      {                           // (assumes non-empty list)
      Link current = first;              // search for link
      Link previous = first;
      while(current.iData != key)
         {
         if(current.next == null)
            return null;                 // didn't find it
         else
            {
            previous = current;          // go to next link
            current = current.next;
            }
         }                               // found it
      if(current == first)               // if first link,
         first = first.next;             //    change first
      else                               // otherwise,
         previous.next = current.next;   //    bypass it
      return current;
      }
// -------------------------------------------------------------
   public void displayList()      // display the list
      {
      System.out.print("List (first-->last): ");
      Link current = first;       // start at beginning of list
      while(current != null)      // until end of list,
         {
         current.displayLink();   // print data
         current = current.next;  // move to next link
         }
      System.out.println("");
      }
// -------------------------------------------------------------
   }  // end class LinkList
////////////////////////////////////////////////////////////////


class LinkList2App
   {
   public static void main(String[] args)
      {
      LinkList theList = new LinkList();  // make list

      theList.insertFirst(22, 2.99);      // insert 4 items
      theList.insertFirst(44, 4.99);
      theList.insertFirst(66, 6.99);
      theList.insertFirst(88, 8.99);

      theList.displayList();              // display list

      Link f = theList.find(44);          // find item
      if( f != null)
         System.out.println("Found link with key " + f.iData);
      else
         System.out.println("Can't find link");

      Link d = theList.delete(66);        // delete item
      if( d != null )
         System.out.println("Deleted link with key " + d.iData);
      else
         System.out.println("Can't delete link");

      theList.displayList();              // display list
      }  // end main()
   }  // end class LinkList2App
////////////////////////////////////////////////////////////////

---------------MY EDITED LINKED LIST BELOW-------------------------------------

import java.util.*;
import java.util.ArrayList;


public class Person<T> {

public T lName;             // data item (key)
public T fName; // data item
public T age; // generic variable 
public Person next;              // next link in list
//-------------------------------------------------------------
public Person(T ln, T fn, T ag) // constructor
{
lName = ln;
fName = fn;
age = ag;
}
//-------------------------------------------------------------
public <T> void displayPerson()      // display Person
{
System.out.print("{" + lName + ", " + fName + ", " + age + "} ");
}
}
//End class Person---------------------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class PersonList<T extends Person<T>>{
private Person<T> first;            // variable of type Person, ref to first link on list

//-------------------------------------------------------------
public PersonList()              // constructor
{
first = null;               // no links on list yet
}
//-------------------------------------------------------------
public <T> void insert(T ln, T fn, T ag)
{                           // make new link
Person newPerson = new Person(ln, fn, ag); // instantiate Object newPerson of class Person
newPerson.next = first;       // it points to old first link
first = newPerson;            // now first points to this
}
//-------------------------------------------------------------
public Person find(T key)      // find link with given key
{                           // (assumes non-empty list)
Person current = first;              // start at 'first'
while(current.lName != key)        // while no match,
{
if(current.next == null)        // if end of list,
return null;                 // didn't find it
else                            // not end of list,
current = current.next;      // go to next link
}
return current;                    // found it
}
//-------------------------------------------------------------
public Person delete(T key)    // delete link with given key
{                           // (assumes non-empty list)
Person current = first;              // search for link
Person previous = first;
while(current.lName != key)
{
if(current.next == null)
return null;                 // didn't find it
else
{
previous = current;          // go to next link
current = current.next;
}
}                               // found it
if(current == first)               // if first link,
first = first.next;             //    change first
else                               // otherwise,
previous.next = current.next;   //    bypass it
return current;
}
//-------------------------------------------------------------
public <T> void displayPersonList()      // display the list
{
System.out.print("----Person List (first-->last): ----");
Person current = first;       // start at beginning of list
while(current != null)      // until end of list,
{
current.displayPerson();   // print data
current = current.next;  // move to next link
}
System.out.println("");
}

}
//End class LinkList-------------------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class LinkList2App
{
public static final int MAX_SIZE = 20;

public static void main(String[] args)
{
System.out.println("\n------Person------");
ArrayList<Person> theList = new ArrayList<Person>(MAX_SIZE);// instantiating the Object 'theList' of type person

theList.insert(new Person("Aceves", "Penny", 1));
theList.insert(new Person("Garza", "Eli", 2));
theList.insert(new Person("Aceves", "Chloe", 4));
theList.insert(new Person("Murray", "Bill", 67));
theList.insert(new Person("West", "Kanye",35 ));
theList.insert(new Person("Farrelly", "Chris", 45));

theList.displayPerson();

// created Person object for search
Person searchPerson = new Person("Murray", "Bill", 67);

// search the newly created Person object
Person foundPerson = theList.find(searchPerson);

theList.displayPersonList();

if(foundPerson != null)
System.out.println("Found last name with key " + foundPerson.lName);
else
System.out.println("Can't find last name");

// delete item
if(foundPerson != null )
System.out.println("Deleted link with last name " + foundPerson.lName);
else
System.out.println("Can't delete name");

theList.displayPersonList();

} // END main()--------------------------------------------------------------------------------------------------------
}/ / END class LinkList2App----------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Post a Reply

Replies

Oldest  Newest  Rating
0 Gary Whitney · October 11, 2015
I debated weather to answer this because I am not an expert.

It appear to me you missed the concept of generics.
Before generics, everything you put in an arrayList came out as an object.
If you added a Cat object into your arraylist that you intended to use to store Dogs, THEN you would get a error when you tried to pull it out and assign it to a different Dog object.

The idea behind <T> is that T represents a type of object.

ArrayList<Person> theList = new ArrayList<Person>
Creates an arraylist named theList that can ONLY accept objects of the type Person.

Generics are for collections not objects and not object members.

The instruction "each link object contains an object of generic type instead of a numeric value"
should have stated "each link object is an object of the specified generic type instead of a numeric value"

There for I would remove at the <T> in your code.

You want an ArrayList that will only contain person objects e.g. ArrayList<Person> theList = new ArrayList<Person>
Change
public class Person<T> {

public T lName; // data item (key)
public T fName; // data item
public T age; // generic variable
public Person next; // next link in list

To
public class Person {

public int id; // key to identify this object
public String fName;
public int age;
public int next; // next link in list

There are more changes you will  have to make but this should give you the idea.

ArrayList<Person> theList = new ArrayList<Person>
Creates an ArrayList named theList that can ONLY accept objects of the type Person.

The order you add them can be used as an index to retrieve them BUT... ArrayList supports and insert method which could break your link. Therefore the instructor uses the next variable to store the id of the next item in the list.
The concept here is that you want each Person object to contain the id of the next item in the list. like a "LinkedList".

I hope I haven't confused you more withe my BRIEF explanation.
  • 1

Java / Android Development

107,195 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator