简体   繁体   中英

Parameterized types in Linked Lists

I have a data structure and I need to compare data to previous elements that occurred at the same time. Something like:

dataStruct{
long startTime;
long endTime;
long data;
}

part of my implementation involves adding these elements to a linked list and comparing data between nodes that exist at overlapping times. Do I need a parameterized type or can I add dataStructures to the list and access their members by the dot operator. Something like:

    dataStructure data = new DataStructure(time, time2, data);
    dataStructure moreData = new DataStructure(time3, time4, data2);

    LinkedList list = new LinkedList();

    list.add(data);

    if(list.peek().endTime > moreData.startTime){
    moreData.data = list.peek().data + moreData.data;
    list.pop();
    }

You should use a parametrized type.

LinkedList<DataStructure> data = new LinkedList<DataStructure>();

This way, you can get a DataStructure instead of an Object out of the LinkedList .

Otherwise, you're using the raw form of the LinkedList class which deals with Object s. It is possible to cast what you get out of the list as a DataStructure , and that would work. But using generics with a parametrized type is preferred; raw types and casting is the old, pre-Java 5 way of operating on collections.

Whether you can access the members directly depends on whether the code that creates and uses these DataStructure s is in the same package, because you have (default) package visibility on the members of DataStructure .

Generally you will want encapsulation on your DataStructure type, with private member variables and public "getter" and "setter" methods that access those values. Then any code can use DataStructure with access to the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM