Retrieve only one specific data in a LinkedList (the data field holds several data)

天涯浪子 提交于 2019-12-10 23:34:33

问题


I implemented the LinkedList class from scratch and they have the following methods: getHead(), getCount(), addFront(), deleteFront()

I have a Student class with constructor(String studentAdmNo, String studentName, String gender, String diploma, int year, String status), get set method, toString()

and the Node contains method getData(), setData(), getLink(), setLink(), toString()

I added the Student object into the LinkedList (and so this LinkedList data field holds several data; which is String studentAdmNo, String studentName, String gender, String diploma, int year, String status).

However, I want to retrieve only one data (which is the year) from the data field.

for (Node j = LinkedList.getHead(); j!=null; j = j.getLink()) 
        {
            int yearData = ((Integer)j.getData()); //returns everything that is in the data field
            //what I want is something like j.getData().getYear() but there's an error
            }
        }

How can I do that?


回答1:


If your Node.getData() method returns an Object and you have used it to store Student objects, then you can cast the returned object to Student and call the appropriate getter.

int year = ((Student)j.getData()).getYear();




回答2:


You should look at this example (continue by clicking the little almost invisible button labled next): Why Generics?

I think you should make your list generic. I guess that it right now contains Objects. In your case, you should declare your classes like class Node<E> and class LinkedList<E>, and create the linked list as such: LinkedList<Student>.

I would also argue against disclosing the Node class. See this for a quick overview: Encapsulation/Information Hiding.

Your getHead() method should instead return a Student directly. Then you could simply do:

list.getHead().getYear();



回答3:


You have getters & setters, so simply get the Node from which you want to retrieve the year and make a call using getter for year Likely the method should be node.getYear(); where node is the instance of Node



来源:https://stackoverflow.com/questions/34761843/retrieve-only-one-specific-data-in-a-linkedlist-the-data-field-holds-several-da

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!