What's the difference between a List and a LinkedList? - list

What is the difference ?
List list = new List();
LinkedList Llist;
list.add(anyString); for example and Llist.AddFirst(anyString);

In which language? In Java (and probably also the language you use) List is just an interface for various types of Lists. You can have single linked lists, double linked lists, circular lists etc.

In Java:
List is an interface, it does not provide a concrete implementation but only the definition of which operations are possible for classes implementing this interface. I.e. each implementation of List must provide a size() method returning the number of elements in the list.
LinkedList is a concrete implementation. It supports all the methods of List (probably some more, specific to its implementation). As the name suggests, it is implementing the interface using the linked list approach.
A different List implementation would be ArrayList, which is internally using an array to implement the interface.
In C#:
In C# the naming is different. List is a concrete implementation of IList. Therefore IList is the interface, and List is the ArrayList implementation. There is also a LinkedList in C#.

First of all, you need to understand Interface and Implementation class in Java.
List is interface and LinkedList is concrete class implementing List interface.
new keyword and constructor symbol () is used to instantiate (create object) for concrete classes, but cannot be used for Interface
List list = new List(); //cannot compile as List is Interface
List list = new ArrayList(); //Valid and can compile
List list = new LinkedList(); //Valid and can compile
Before you go deep into java.util.Collection package, you should learn basic Java well.

Assuming Java.in java there are many libraries that we can work from each has its own objects
so List belong to java.awt library while LinkedList belongs to java.util.
about add and addFirst()
I think the difference will be like this
list.add(A)
list.add(B)
list.addFirst(C)
if you printed the list you will find the order is C A B
hope it helped

Related

How can I implement Collection/List interface or abstract class in Kotlin?

I'm having trouble implementing the iterator and get set functions. (Edit: By trouble I mean that I don't know how to do it and I need help)
In the past, I've inherited from ArrayList even though I need a fixed-size collection.
I've also used an Array property in my class and added a get and a set operator funcions, but these two solutions just feel like unnecessary workarounds.
Edit: I just found out that Kotlin itself doesn't have a List implementation yet (it uses ArrayList instead), So maybe I'm not supposed to be able to Implement it. I'm going to keep this open just in case.
There is a very neat feature in Kotlin that allows you to easily implement the List interface by Delegation. Just use the by operator on a list property, then the class will delegate all methods of the List interface to that property. So, for example, instead of,
class Cars {
private val cars = ArrayList<Car>()
}
you write:
class Cars(
private val cars: MutableList<Car> = ArrayList<Car>()
): MutableList<Car> by cars
Now Cars implements List, and can be used just as such:
val cars = Cars()
cars.add(Car())
for (car in cars)
car.vroom()

array and object declaration

I'm trying to create an array list of objects. I am a student and my professor requires that all declaration are before the executable code and that all instantiations or initializations (not sure which term) are done in the executable code. I'm new to the List or ArrayList concept and i can't quite figure out how to get this started.
List <Room> roomAry; //declare array object for rooms
//initialize room array
roomAry = new List<Room>();
This keeps telling me it can't compile.
The error follows:
List is abstract; cannot be instantiated roomAry = new List
();
Because it should be roomAry = new ArrayList<Room> (). It's correct for both .NET and JAVA.
List is just an interface (JAVA)
The error is telling you exactly what the problem is. The List is an interface and is thus abstract. You cannot create an instance of an abstract class or an interface; you always have to create an instance of a concrete class.
Please see the All Known Implementing Classes: section under the List interface in the javadocs. (Note that if the implementing class itself is abstract, then you cannot use it)
So you can use one of the implementing classes for the instantiation. One of the simpler ones is ArrayList.
roomAry = new ArrayList<Room>();

C++ Extending an Array Class (OOP)

Is it possible to derive a child from an array Class?
What I am playing with right now is:
Creating an array of Linked Lists
I am building a List class from which I can derive different types of lists (ie. Linear, Circular, Double Linked, etc...
What I would like to do is to extend an array class to make a "arrayOfLists" class. Then I would take the child class and add to it a LinkedList object member.
Is this possible? Am I even thinking of OOP correctly in this instance?
Thank you for your help
The fact that you're talking about it as an arrayOfLists class is a pretty good clue that inheritance is the wrong tool for this job.
Inheritance (public inheritance, anyway) should only be used when the derived class can be substituted for the base class under any possible circumstances. In other words, that an arrayOfLists could be used anywhere a List could be used. Although that might be possible, it seems fairly unlikely.
It sounds to me like what you want is really just an array-like template (e.g., std::vector) instantiated over one of your linked list classes.

A list containing objects of two different classes in C++

I feel more fluent in Java than C++ so I will try to explain what I want to "transport" in a few words. In Java you could create an ArrayList containing objects of 2 or more classes that one of them inherited from another. Let me illustrate. Let's say we have:
class Vehicle
{
...
}
class Car extends Vehicle
{
...
}
You could then do something like that Car a = new Vehicle ([arguments]);
And then you could add objects of both Vehicle and Car to the same ArrayList created as following:
ArrayList ar = new ArrayList<Car>();
Now to my problem, in C++ I have manually written the code to create a simple linked list. Each node of this list is described below:
struct clientListNode
{
vip* cust;
struct clientListNode* next;
};
vip is another class which is derived from customer.Is there any way to allow my list to accept both objects of vip class and customer class?
Polymorphism works the other way. You can use a customer* pointer to point to a vip object, but not the other way. (This is related to the Liskov-substitution principle.)
So if you had a customer* in your clientListNode class, it would accept both vip* and customer* pointers.
However, I don't think you should reinvent the wheel and implement a linked list from the ground. You should look into the STL (Standard Template Library) which already has solutions for problems like this. For instance, it already has an implementation of the linked list, std::list.
You have to template std::list with the base type you'd like to use it with, but it is important that you cannot use the type directly as a value (std::list<cust>), because that would physically store cust instances in memory, in which you cannot fit the more specific vip type (slicing would occur).
Instead you have to use some kind of handle as the template parameter, you can use a native pointer (std::list<cust*>), but that way you have to manage memory deallocation, or - more preferably - you can use a smart pointer, like shared_ptr (std::list<std::shared_ptr<cust>>), that way the created objects are going to get destroyed automatically.
I doubt you could make Car = new Vehicle even in java, but the other way around makes sense.
What you're after is called "polymorphic collection". C++ standard lib does not have one out of the box, but you can approximate it with a collection of shared_ptr<Vehicle> s or unique_ptr<Vehicle> s. The former would fork very close to a java equivalent.
3rd party libraries may have ready to use polymorphic collections, you can use the term for search.
If customer is the base class, then the cust field of the node should be of type customer*, and it will gladly accept both customers and vips.

Is "node" an ADT? If so, what is its interface?

Nodes are useful for implementing ADTs, but is "node" itself an ADT? How does one implement "node"? Wikipedia uses a plain old struct with no methods in its (brief) article on nodes. I googled node to try and find an exhaustive article on them, but mostly I found articles discussing more complex data types implemented with nodes.
Just what is a node? Should a node have methods for linking to other nodes, or should that be left to whatever owns the nodes? Should a node even be its own standalone class? Or is it enough to include it as an inner struct or inner class? Are they too general to even have this discussion?
A node is an incredibly generic term. Essentially, a node is a vertex in a graph - or a point in a network.
In relation to data structures, a node usually means a single basic unit of data which is (usually) connected to other units, forming a larger data structure. A simple data structure which demonstrates this is a linked list. A linked list is merely a chain of nodes, where each node is linked (via a pointer) to the following node. The end node has a null pointer.
Nodes can form more complex structures, such as a graph, where any single node may be connected to any number of other nodes, or a tree where each node has two or more child nodes. Note that any data structure consisting of one or more connected nodes is a graph. (A linked list and a tree are both also graphs.)
In terms of mapping the concept of a "node" to Object Oriented concepts like classes, in C++ it is usually customary to have a Data Structure class (sometimes known as a Container), which will internally do all the work on individual nodes. For example, you might have a class called LinkedList. The LinkedList class then would have an internally defined (nested) class representing an individual Node, such as LinkedList::Node.
In some more cruder implementations you may also see a Node itself as the only way to access the data structure. You then have a set of functions which operate on nodes. However, this is more commonly seen in C programs. For example, you might have a struct LinkedListNode, which is then passed to functions like void LinkedListInsert(struct LinkedListNode* n, Object somethingToInsert);
In my opinion, the Object Oriented approach is superior, because it better hides details of implementation from the user.
Generally you want to leave node operations to whatever ADT owns them. For example a list should have the ability to traverse its own nodes. It doesn't need to the node to have that ability.
Think of the node as a simple bit of data that the ADT holds.
In the strictest terms, any assemblage of one or more primitive types into some kind of bundle, usually with member functions to operate on the data, is an Abstract Data Type.
The grey area largely comes from which language you operate under. For example, in Python, some coders consider the list to be a primitive type, and thus not an ADT. But in C++, the STL List is definitely an ADT. Many would consider the STL string to be an ADT, but in C# it's definitely a primitive.
To answer your question more directly: Any time you are defining a data structure, be it struct or class, with or without methods, it is necessarily an ADT because you are abstracting primitive data types into some kind of construct for which you have another purpose.
An ADT isn't a real type. That's why it's called an ADT. Is 'node' an ADT? Not really, IMO. It can be a part of one, such as a linked list ADT. Is 'this node I just created to contain thingys' an ADT? Absolutely not! It's, at best, an example of an implementation of an ADT.
There's really only one case in which ADT's can be shown expressed as code, and that's as templated classes. For example, std::list from the C++ STL is an actual ADT and not just an example of an instance of one. On the other hand, std::list<thingy> is an example of an instance of an ADT.
Some might say that a list that can contain anything that obeys some interface is also an ADT. I would mildly disagree with them. It's an example of an implementation of an ADT which can contain a wide variety of objects that all have to obey a specific interface.
A similar argument could be made about the requirements of the std::list's "Concepts". For instance that type T must be copyable. I would counter that by saying that these are simply requirements of the ADT itself while the previous version actually requires a specific identity. Concepts are higher level than interfaces.
Really, an ADT is quite similar to a "pattern" except that with ADT's we're talking about algorithms, big O, etc... With patterns we're talking about abstraction, reuse, etc... In other words, patterns are a way to build something that's implementations solve a particular type of problem and can be extended/reused. An ADT is a way to build an object that can be manipulated through algorithms but isn't exactly extensible.
Nodes are a detail of implementing the higher class. Nodes don't exist or operate on their own- they only exist because of the need for separate lifetimes and memory management than the initial, say, linked list, class. As such, they don't really define themselves as their own type, but happily exist with no encapsulation from the owning class, if their existence is effectively encapsulated from the user. Nodes typically also don't display polymorphism or other OO behaviours.
Generally speaking, if the node doesn't feature in the public or protected interface of the class, then don't bother, just make them structs.
In the context of ADT a node is the data you wish to store in the data structure, plus some plumbing metadata necessary for the data structure to maintain its integrity. No, a node is not an ADT. A good design of an ADT library will avoid inheritance here because there is really no need for it.
I suggest you read the code of std::map in your compiler's standard C++ library to see how its done properly. Granted, you will probably not see an ADT tree but a Red-Black tree, but the node struct should be the same. In particular, you will likely see a lightweight struct that remains private to the data structure and consisting of little other than data.
You're mixing in three mostly orthogonal concepts in your question: C++, nodes, ADTs.
I don't think it's useful to try to sort out what can be said in general about the intersection of those concepts.
However, things can be said about e.g. singly linked list nodes in C++.
#include <iostream>
template< class Payload >
struct Node
{
Node* next;
Payload value;
Node(): next( 0 ) {}
Node( Payload const& v ): next( 0 ), value( v ) {}
void linkInFrom( Node*& aNextPointer )
{
next = aNextPointer;
aNextPointer = this;
}
static Node* unlinked( Node*& aNextPointer)
{
Node* const result = aNextPointer;
aNextPointer = result->next;
return result;
}
};
int main()
{
using namespace std;
typedef Node<int> IntNode;
IntNode* pFirstNode = 0;
(new IntNode( 1 ))->linkInFrom( pFirstNode );
(new IntNode( 2 ))->linkInFrom( pFirstNode );
(new IntNode( 3 ))->linkInFrom( pFirstNode );
for( IntNode const* p = pFirstNode; p != 0; p = p->next )
{
cout << p->value << endl;
}
while( pFirstNode != 0 )
{
delete IntNode::unlinked( pFirstNode );
}
}
I first wrote these operations in Pascal, very early eighties.
It continually surprises me how little known they are. :-)
Cheers & hth.,