In the oracle Java docs: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html:
.element() "Retrieves, but does not remove, the head (first element) of this list."
.peek() "Retrieves, but does not remove, the head (first element) of this list."
Is there a reason that you would want to use .element() as opposed to .peek()?
Is the answer to (1) is "No", why would a class need two methods with the same function?
There are 4 methods.
Peek
Element
Poll
Remove
The behaviour of peek and element is almost same with a difference:
If a queue doesnt contain any elements the peek() method returns null.
The element() method behaves like peek(), so it again retrieves the value of the first element without removing it.
However, if the list is empty element() throws a NoSuchElementException.
Lastly, there are two other methods poll and remove.
The poll() method retrieves the value of the first element of the queue by removing it from the queue. If the list doesnt contain any elements, it will return null but doesnt throw any exception.
The remove() method behaves as the poll() method, so it removes the first element of the list and if the list is empty it will throw a NoSuchElementException.
Reference:
http://www.davismol.net/2014/04/04/java-ocpjp7-difference-between-element-peek-poll-and-remove-methods-of-the-queue-interface/
The behavior is described in the docs for Queue. Basically element throws an exception if there is an error (think empty list) whereas peek just returns a special value (probably null). https://docs.oracle.com/javase/7/docs/api/java/util/Queue.html
Related
When I add a custom class object into a queue, and get it back by remove. The contents of the object is changed.
For example, I set the priority of the shopper to 10, then I add it to the queue, then remove it and check the priority again, which doesn't return 10. This works perfectly with other data types like int. Not sure why it is not working with the type. Any possible source of error?
//main.cpp
PriorityQueueSearch<Shopper> b;
Shopper temp(10);
b.add(temp);
Shopper removed = b.remove();
std::cout<<removed.getPriority();
Thank you for trying to help. PriorityQueueSearch was just a subclass of array implementation of queue (ArrayQueue class). And Shopper was just class with random priority as one of its variables.
The error was in the overloaded operator. Apparently, I was overloading the assignment operator (=), when I wanted to overload the comparison operator(==). Adding that extra '=' to the function prototype got rid of the problem.
Advice to myself would be is to pay closer attention to what I am typing.
when it doesn't return any value, what are it essence?. And most method with void I have seen have println in is block of statements. what println display is it not a value? what determine is usage(void type method)?
Note: I am novice to programming. And all answers I have seen on void type method are about , doesn't return value.
If a function returns void, it means any action the function does is through "side-effects".
Side effects are when a function directly changes the state of something external to the function itself.
When you have a function that prints to the screen using println, it's modifying the global output stream (which is outside of the function) by inserting into it whatever text you gave it.
Keep in mind though functions can have side effects and return a value at the same time. A pop operation usually modifies the stack object by removing an element from it (side effects), then returns whatever object it popped.
Side effects aren't necessary in most cases, but they can be useful. In the above pop example, if the method didn't modify the stack directly, it would need to return both a new stack with an element removed, and the removed element. Two things are returned at once usually by wrapping them in something like a tuple.
If your code returns everything and relies on side effects as little as possible, it's known as functional code. If you have code that relies on side effects, it's known as imperative code (gross simplification, but it gets the idea accross).
I am retrieving a list of items using Entity Framework and if there are some items retrieved I do something with them.
var items = db.MyTable.Where(t => t.Expiration < DateTime.Now).ToList();
if(items.Count != 0)
{
// Do something...
}
The if statement could also be written as
if(items.Count() != 0)
{
// Do something...
}
In the first case, the .Count is a List<T>.Count property. In the second case, the .Count() is IEnumerable<T>.Count() extension method.
Although both approaches achieve the same result, however, is one more preferred than the other? (Possibly some difference in performance?)
Enumerable.Count<T> (the extension method for IEnumerable<T>) just calls Count if the underlying type is an ICollection<T>, so for List<T> there is no difference.
Queryable.Count<T> (the extension method for IQueryable<T>) will use the underlying query provider, which in many cases will push the count down to the actual SQL, which will perform faster than counting the objects in memory.
If a filter is applied (e.g. Count(i => i.Name = "John")) or if the underlying type is not an ICollection<T>, the collection is enumerated to compute the count.
is one more preferred than the other?
I generally prefer to use Count() since 1) it's more portable (the underlying type can be anything that implements IEnumerable<T> or IQueryable<T>) and 2) it's easier to add a filter later if necessary.
As Tim states in his comment, I also prefer using Any() to Count() > 0 since it doesn't have to actually count the items - it will just check for the existence of one item. Conversely I use !Any() instead of Count() == 0.
It depends on the underlying collection and where Linq will be pulling from. For example if it's SQL then using .ToList() will cause the query to pull back the entire list, and then count it. However, the .Count() extension method will translate it into a SQL COUNT statement on the database side. In which case there will be an obvious performance difference.
For just a standard List or Collection it's as stated in D. Stanley's answer.
I would say that it depends on what's going on inside the if block. If you're simply doing the check to determine whether to perform a sequence of operations on the underlying enumeration, then it's probably not needed in any event. Simply iterate over the enumeration (omitting ToList as well). If you're not using the collection inside the if block, then you should avoid using ToList and definitely use Any over any Count/Count() method.
Once you've performed the ToList then you're no longer using Entity Framework and I expect that Count() is only marginally slower than Count since, if the underlying collection is ICollection<T> it defers to that implementation. The only overhead would be determining whether it implements that interface.
http://msdn.microsoft.com/en-us/library/bb338038.aspx
Remarks:
If the type of source implements ICollection<T>, that implementation is used to obtain the count of elements. Otherwise, this method determines the count.
I'm using SortedDictionaries to simulate a Queue (due to some requirements that I have), and I'm calling Last() over the sorted dictionary to get the item that I need to dequeue.
I was just wondering about the performance of using a custom comparer and calling First() or keep calling Last().
After decompiling the .NET 3.5 assemblies, I found that the SortedDictionary class does have a Count property, so I'm guessing the framework just returns the item at position 0 when First is called, and the item at position [count-1] when Last is called, am I right?
No.
Since SortedDictionary does not implement IList<TValue> (which has a this[int] indexer), Last() has no choice but to iterate through the whole thing.
The Last method is an extension method in the Enumerable class. The implementation of Last first tries to cast the IEnumerable (your SortedDictionary) to IList<T>. If it can, then it uses the Count property to directly access the last element. If it can't, then it has to iterate over all elements to get to the last one. SortedDictionary doesn't implement IList<T>, so Last will iterate over all elements.
If you look at the Container ADT (abstract data type) as a black box, it provides two functions:
1. put(C, x)
2. get(C)
The first function will put the object x into container C. The second will retrieve the "next" object from container C, where "next" depends on what type of container you want. A stack implementation would return the element that was most recently put into the container (also known as a FILO ADT).
My question is, in it's most generic form, does the Container ADT function get() remove the element itself from the container, or does it simply return a reference to it for access, retaining the element in the Container?
if you have only put() and get(), get() must also remove the element, otherwise you won't have access to the nth element for each n!=1.
the idea is with enough get() oporations, you should be able to access each element in the container, and if get() doesn't remove the element, sequential get()'s will always return the same element, so only the first element is accessable.
but it can be different for each implementation, of course. (for example, you can create a ADT with put(), get() and pop(), where get will only return the element.