Valentin Stamate
Valentin Stamate

Reputation: 1439

How to assign the object type for a list in java?

Let's say that I have a class :

class Person{
  String name = "";
  int age = 0;
  Person(String name, String age){
    this.name = name;
    this.age = age;
  }
}

I implemented my own List but I don't know how to specify the object type like traditional List : List<Person>. If I let the default class to "Object" it works but I cannot access the variables and methods from my object. For example print( list.get(0) ) is going to show the reference for my object but print( list.get(0).name ) it's not going to work. I want for my list to work on any class.

This is how I declare my implemented list :

List list = new List();
list.add( new Person("Andrei", 19) );

Here is my code : link

Upvotes: 0

Views: 1543

Answers (3)

Conffusion
Conffusion

Reputation: 4475

You should make your LinkedList generic and also the embedded Node so you can define the data field in Node as an instance of your passed type:

class Node<T>{
    T data;// Object data
    Node next;

    Node(T d){
        this.data = d;
        this.next = null;
    }
}
public class LinkedList<T> {
    Node<T> first = null;
    Node<T> last = null;
    // TODO change all your methods to accept value of type T instead of Object
}

Upvotes: 1

IQbrod
IQbrod

Reputation: 2265

Your list class should use generics

public class MyList<T> {
    public T getAtIndex(int i) {
        return ...;
    }
}

Then you can create one like this

MyList<Person> = new MyList<Person>();

I would also suggest to extend List with

public class MyList<T> extends List<T>

Which provides standard methods such as get

@Override
public T get(int index) {
    return ...;
}

Upvotes: 0

Abra
Abra

Reputation: 20914

In the code you linked to from your question, your LinkedList class is not generic. To make it generic you can define it as follows...

public class LinkedList<T> {
}

However, since your LinkedList class contains only Nodes, you should rather just make your Node class generic. Something like...

class Node<T> {
    T data;
    Node next;

    Node(T d){
        this.data = d;
        this.next = null;
    }
}

Then you can create a Person Node like so...

Node<Person> personNode = new Node<>(new Person("George", 20));

By the way, I suggest renaming your LinkedList class since there is already such a class in the standard java library of classes.

Upvotes: 0

Related Questions