Making a list of objects of generic type.

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-------------------------------------

Post a Reply

Replies

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 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

124,370 followers

About

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