I need to create a FIFO queue. I was thinking in creating a LinkedList for that, because of it's native methods to remove and add. But my queue should have a fixed size, so how could I fix that size?
Thanks in advance!
The easiest thing would be use one of the implementations of java.util.Deque or java.util.Queue
You can wrap an instance of a LinkedList in your own class, and control the size (composition). The downside (or upside, based on your preference) of this is that you can control which methods to explose, in this case add and remove. Another alternative is to extend LinkedList and override add/remove while controlling the size.
If you must have a fixed size, then you ought to use an ArrayList (or just an array) to back the FIFO.... Just keep a variable representing the index of the head, and a variable representing the index of the tail and move them around as you push and pop.
However, if this isn't homework, you should probably just use one of the many available Collections classes. They do the job very well.
Related
Are deques (double-ended queues) traversable data structures? Does it make a difference whether they are have an array-based implementation vs linked implementation?
Yes, deques is traversable data structure, you can get interator from deque for traversing. Functionally, It does not make difference. But, technically and data structure wise, it make a difference. Remember, when we are using list we can add node dynamically. But, when using array, we need to define the size of deque or default size is used. Now, if you insert another element then it will create new array of double size and copy old array into new array then insert the new element.
Yes, they are traversable. Especially in JAVA Deque API, you can always get either iterator (or) descendingIterator to traverse the Deque either from first to last (or) from last to first respectively.
For just traversing the Deque, the underlying implementation may not make much difference. But for other operations it does. People usually prefer ArrayDeque over LinkedList. For more information on this follow the thread Why is ArrayDeque better than LinkedList.
Also look at the corresponding JAVA APIs to get the major differences between these two different implementations.
No. Like the structures it is a hybrid of (i.e., stacks and queues), deques (or double-ended queues) are not designed to be traversable. In fact, they are specifically designed not to be traversable. If the capability of traversing items contained within is necessary for a particular application, then a dequeue is probably not the best data structure to use in that case.
I am considering using a Java collection that would work best with random insertions. I will be inserting a lot and only read the collection once at the end.
My desired functionality is adding an element at a specified index, anywhere between <0, current_length>. Which collection would be the most efficient to use?
Useful link for your reference:
http://www.coderfriendly.com/wp-content/uploads/2009/05/java_collections_v2.pdf
Not entirely sure how you will be reading the information post input (and how important it is to you). Hashmap or ArrayList would make sense depending on what you are looking to do. Also not sure if you are looking for something thread safe or not.
Hope it helps.
The inefficiency of using List is endemic to the problem. Every time you add something, every subsequent element will have to be re-indexed - as the javadoc states:
Shifts the element currently at that position (if any) and any
subsequent elements to the right (adds one to their indices).
From your question/comments, it would appear that you have a bunch of Objects, and you're sorting them as you go. I'd suggest a more efficient solution to this problem would be to write a Comparator (or make your object implement Comparable), and then use Collections.sort(list, comparator) (or Collections.sort(list)).
You might suggest that your Objects are being sorted on the basis of other variables. In which case, you could create an extension of the Object, with those other variables as fields and extending Comparable, and with a method like getOriginal(). You add these wrapped objects to your list, sort, and then iterate through the list, adding the original objects (from getOriginal()) to a new list.
For info on the sorting algorithm of collections - see this SO question
I'm making a top-bottom queue. Do I use array or arraylist?
I'm not sure what you mean by "top-bottom" queue, and neither does google, but in general an array is not a good choice for a queue. In queues, you insert at the front and remove from the back (FIFO). In an array, insertion to the front of the array requires copying all of the elements in the existing array over to the right one, requiring O(n) time. If you only have a few items in the queue, that's not much of an issue, but if you have a lot of items, it's obviously very wasteful.
A doubly linked list with head and tail pointers would be better, but you should just use a Queue instead.
If it is fixed as you said above, i.e. it always will have up to 10 things, I'd use a array because arrays are fixed and they are more maneuverable. The arraylist can grow, but the API for it is a lot smaller than the array.
I'd use ArrayList, since it's effectively an array with a nicer API. Use the constructor that takes an initialCapacity argument to make it allocate the right amount of memory up-front, and don't call any methods that would cause it to resize itself.
Depends on how you are going to fill it:
If you are going to fill it in random order, you may be better with an array, otherwise I'd go with ArrayList or List to avoid all the "Redim"s.
You could use a LinkedBlockingQueue or an ArrayBlockingQueue which can be bounded (fixed size). An array could be a solution but you would need to reimplement the queue logic. Lists are not bounded so nothing prevents you from making them bigger than expected, unless you add some code. The queues do all that for you.
I wouldn't use either an array or an ArrayList. I would use a LinkedList. You need to insert at the back and remove from the front, and these operations are O(n) on arrays, and O(1) on linked lists.
If I am going to create a Java Collection, and only want to fill it with elements, and then iterate through it (without knowing the necessary size beforehand), i.e. all I need is Collection<E>.add(E) and Collection<E>.iterator(), which concrete class should I choose? Is there any advantage to using a Set rather than a List, for example? Which one would have the least overhead?
which concrete class should I choose?
I would probably just go with an ArrayList or a LinkedList. Both support the add and iterator methods, and neighter of them have any considerable overhead.
Is there any advantage to using a Set rather than a List, for example?
No, I wouldn't say so. (Unless you rely on the order of the elements, in which case you must use a List, or want to disallow duplicates, in which case you should use a Set.)
(I don't see how any Set implementation could beat a list implementation for add / iterator methods, so I'd probably go with a List even if I don't care about order.)
Which one would have the least overhead?
Sounds like micro benchmarking here, but if I'd be forced to guess, I'd say ArrayList (or perhaps LinkedList in coner cases where ArrayLists need to reallocate memory often :-)
Do not go with a Set. Sets and Lists differ according to their purpose, that you should always consider when choosing the right Collection
a List is there for maintaining elements in the order you added them; and if you insert the same element twice it will be kept twice
a Set is there for holding one specific element exactly once (uniqueness); order is only relevant for specific implementations (like TreeSet), but still elements that are 'the same' would not be added twice
Set is only meaningful if you want to sort your objects and to make sure no duplicate element is 'registered'. Else, an ArrayList is just fine.
However, if you want to add elements while iterating too, an ArrayBlockingQueue is better.
Here are some key points which can help you to choose your collection according to your requirement -
List(ArrayList or LinkedList)
Allowed duplicate values.
Insertion order preserved.
Set
Not allowed duplicate values.
Insertion order is not preserved.
So according to your requirement List seems to be a suitable choice.
Now Between ArrayList and LinkedList -
ArrayList is a random access list. Use if your frequent operation is the retrieval of elements.
LinkedList is the best option if you want to add or remove elements from the list.
I have the following problem in my Data Structures and Problem Solving using Java book:
Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.
First, I believe it is asking you to write a method. Like:
void printReverseList(Collection col) {}
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).
That could technically count as 1 routine (all have the same name).
I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.
You might want to read this.
Isn't there a base Collection class?
Probably worth looking here as a starting point: Collections.