how to initialize PriorityQueue - priority-queue

I'm reading the API http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html. I'm still a bit lost.
Which is the right way to initialize?
PriorityQueue(Caller caller_pq);
or
static PriorityQueue<Caller> caller_pq;
caller_pq = new PriorityQueue<Caller>();

If caller_pq is the variable you want to hold your PriorityQueue then the second one --
static PriorityQueue<Caller> caller_pq;
caller_pq = new PriorityQueue<Caller>();
-- is correct.
It's hard to tell what you mean by your first option PriorityQueue(Caller caller_pq). If you're intending to create a PriorityQueue containing elements of type Caller (which is what I think you're intending), then no, that won't work.
If Caller implements Collection or extends PriorityQueue then it will make a PriorityQueue containing the elements in caller_pq (as long as you precede it with new).

Related

Is the `def` keyword optional? If so, why use it?

I am aware that a variable can be dynamically typed with the def keyword in Groovy. But I have also noticed that in some circumstances it can be left out, such as when defining method parameters, eg func(p1, p2) instead of func(def p1, def p2). The latter form is discouraged.
I have noticed that this is extendable to all code - anytime you want to define a variable and set its value, eg var = 2 the def keyword can be safely left out. It only appears to be required if not instantiating the variable on creation, ie. def var1 so that it can be instantiated as a NullObject.
Is this the only time def is useful? Can it be safely left out in all other declarations, for example, of classes and methods?
Short answer: you can't. There are some use cases where skipping the type declaration (or def keyword) works, but it is not a general rule. For instance, Groovy scripts allow you to use variables without specific type declaration, e.g.
x = 10
However, it works because groovy.lang.Script class implements getProperty and setProperty methods that get triggered when you access a missing property. In this case, such a variable is promoted to be a global binding, not a local variable. If you try to do the same on any other class that does not implement those methods, you will end up getting groovy.lang.MissingPropertyException.
Skipping types in a method declaration is supported, both in dynamically compiled and statically compiled Groovy. But is it useful? It depends. In most cases, it's much better to declare the type for a better readability and documentation purpose. I would not recommend doing it in the public API - the user of your API will see Object type, while you may expect some specific type. It shows that this may work if your intention is to receive any object, no matter what is its specific type. (E.g. a method like dump(obj) could work like that.)
And last but not least, there is a way to skip type declaration in any context. You can use a final keyword for that.
class Foo {
final id = 1
void bar(final name) {
final greet = "Hello, "
println greet + name + "!"
}
}
This way you can get a code that compiles with dynamic compilation, as well as with static compilation enabled. Of course, using final keyword prevents you from re-assigning the variable, but for the compiler, this is enough information to infer the proper type.
For more information, you can check a similar question that was asked on SO some time ago: Groovy: "def" keyword vs concrete type
in Groovy it plays an important role in Global and Local variable
if the variable name is same with and without def
def is considered local and without def its global
I have explained here in detail https://stackoverflow.com/a/45994227/2986279
So if someone use with and without it will make a difference and can change things.

If instances are really just pointers to objects in Python, what happens when I change the value of a data attribute in a particular instance?

Suppose I define "Class original:" and create a class attribute "one = 4." Then I create an instance of the class "First = original()." My understanding is that First now contains a pointer to original and "First.one" will return "4." However, suppose I create "Second = original()" and then set "Second.one = 5." What exactly happens in memory? Does a new copy of Class original get created with a class attribute of 5?
I've created a Class original with class attribute one. I then created two instances of this class (First and Second) and verified that id(First.one) and id(Second.one) are pointing to the same place. They both return the same address. However, when I created Third=original() and set Third.one = 5 and then check id(Thrid.one) it appears to be pointing somewhere else. Where is it pointing and what happened? When I check original.one it still returns "4" so obviously the original object is not being modified. Thanks.
It appears you are asking about a piece of code similar to this:
class Original:
def __init__(self, n):
self.one = n
first = Original(4)
second = Original(4)
third = Original(5)
print(id(first.one))
# 140570468047360
print(id(second.one))
# 140570468047360
print(id(third.one))
# 140570468047336
Suppose I define "Class original:" and create a class attribute "one = 4." Then I create an instance of the class "First = original()." My understanding is that First now contains a pointer to original
No. The variable references the instance you created, not the class. If it referenced the class, there would be no way for you to get at the instance you just created.
The instance will, somewhere in its object header, of course contain a pointer to its class. Without that pointer, method lookup wouldn't be possible, since you wouldn't be able to find the class from the instance.
and "First.one" will return "4."
Yes. The attribute one of first contains a pointer to the object 4 (which is an instance of the class int).
[Note that technically, some Python implementations will perform an optimization and actually store the object 4 directly in the attribute instead of a pointer to the object. But that is an internal implementation detail.]
However, suppose I create "Second = original()" and then set "Second.one = 5." What exactly happens in memory? Does a new copy of Class original get created with a class attribute of 5?
No. Why would you need a separate copy of the class? The methods are still the same for both instances. In fact, that is precisely the reason why methods in Python take the instance as their first argument! That way, there need only be one method. (This is actually the same in every OO language, except that in most other languages, this argument is "invisible" and only accessible using a special keyword like self in Ruby, Smalltalk, Self, and Newspeak or this in Java, C#, and Scala.)
I've created a Class original with class attribute one. I then created two instances of this class (First and Second) and verified that id(First.one) and id(Second.one) are pointing to the same place. They both return the same address. However, when I created Third=original() and set Third.one = 5 and then check id(Thrid.one) it appears to be pointing somewhere else.
It is not quite clear to me what your question is here. first.one and second.one both point to 4, so they both point to the same ID since they both point to the same object. third.one points to 5, which is obviously a different object from 4, so naturally, it has a different ID.
It is, in fact, one of the requirement of IDs that different objects that exist at the same time must have different IDs.
Where is it pointing and what happened?
Again, it is not quite clear what you are asking.
It is pointing at 5, and nothing happened.
When I check original.one it still returns "4" so obviously the original object is not being modified.
Indeed, it isn't. Why would it be?

Referencing an instance of a given class in sequence diagrams

I have to model a system where an object of the class Person will invoke the static method getBook(...) : Book on the class Book which will return an instance of a particular book.
How do you reference the book instance obtained by the operation?
As of now, I can think of two approaches, neither of which I have ever seen/used, which is why I am looking for the correct approach.
The first approach is to invoke methods directly on the book instance obtained, e.g. if the reference returned by getBook(...) : Book is named matchingBook, I would use matchingBook.doSomething(...), much like having a local variable.
The second way, which I find more in the line of sequence diagrams is to let the book instance returned by the operation appear with its own lifeline, e.g. next to the Book class, and referencing it with an arrow labeled doSomething(...).
However, with the second approach, it is not that obvious that this object is in fact the one returned by the operation.
The second approach is the correct. To show that you are pointing to the returned object (matchingBook), you can add the variable name to the title of the lifeline, like this:
The second approach is the correct one. Anytime you call operations on an object returned by a first operation, you can't do better than a name match between the result of the first call and the lifeline.
Anyway I don't really understand what you expect of the first way: where would you put matchingBook.doSomething(...)? on a arrow pointing which lifeline?

Storing object in Esent persistent dictionary gives: Not supported for SetColumn Parameter error

I am trying to save an Object which implements an Interface say IInterface.
private PersistentDictionary<string, IInterface> Object = new PersistentDictionary<string, IInterface>(Environment.CurrentDirectory + #"\Object");
Since many classes implement the same interface(all of which need to cached), for a generic approach I want to store an Object of type IInterface in the dictionary.
So that anywhere I can pull out that object type cast it as IInterface and use that object's internal implementation of methods etc..
But, as soon as the Esent cache is initialized it throws this error:
Not supported for SetColumn
Parameter name: TColumn
Actual value was IInterface.
I have tried to not use XmlSerializer to do the same but is unable to deserialize an Interface type.Also, [Serializable] attribute cannot be used on top of a Interface, so I am stuck.
I have also tried to make all the implementations(classes) of the Interface as [Serializable] as a dying attempt but to no use.
Does any one know a way out ? Thanks in advance !!!
The only reason that only structs are supported (as well as some basic immutable classes such as string) is that the PersistentDictionary is meant to be a drop-in replacement for Dictionary, SortedDictionary and other similar classes.
Suppose I have the following code:
class MyClass
{
int val;
}
.
.
.
var dict = new Dictionary<int,MyClass>();
var x = new MyClass();
x.val = 1;
dict.Add(0,x);
x.val = 2;
var y = dict[0];
Console.WriteLine(y.val);
The output in this case would be 2. But if I'd used the PersistentDictionary instead of the regular one, the output would be 1. The class was created with value 1, and then changed after it was added to the dictionary. Since a class is a reference type, when we retrieve the item from the dictionary, we will also have the changed data.
Since the PersistentDictionary writes the data to disk, it cannot really handle reference types this way. Serializing it, and writing it to disk is essentially the same as treating the object as a value type (an entire copy is made).
Because it's intended to be used instead of the standard dictionaries, and the fact that it cannot handle reference types with complete transparency, the developers instead opted to support only structs, because structs are value types already.
However, if you're aware of this limitation and promise to be careful not to fall into this trap, you can allow it to serialize classes quite easily. Just download the source code and compile your own version of the EsentCollections library. The only change you need to make to it is to change this line:
if (!(type.IsValueType && type.IsSerializable))
to this:
if (!type.IsSerializable)
This will allow classes to be written to the PersistentDictionary as well, provided that it's Serializable, and its members are Serializable as well. A huge benefit is that it will also allow you to store arrays in there this way. All you have to keep in mind is that it's not a real dictionary, therefore when you write an object to it, it will store a copy of the object. Therefore, updating any of your object's members after adding them to the PersistentDictionary will not update the copy in the dictionary automatically as well, you'd need to remember to update it manually.
PersistentDictionary can only store value-structs and a very limited subset of classes (string, Uri, IPAddress). Take a look at ColumnConverter.cs, at private static bool IsSerializable(Type type) for the full restrictions. You'd be hitting the typeinfo.IsValueType() restriction.
By the way, you can also try posting questions about PersistentDictionary at http://managedesent.codeplex.com/discussions .
-martin

linked list MutableString homework inheriting vs delegation

I have a linked list question that stems from this homework prompt I am about to post. it might help with the answer:
Specifics
The Java String class is immutable (you cannot change the contents). This is sometimes a hindrance to what you want to do with a string (i.e. make changes to the existing string). So, for this assignment you will create a class called MutableString. NOTE/DISCLAIMER: The Java API does have a class StringBuffer, which is mutable, but for the intents and purposes of this assignment we'll pretend we don't know about it ;-)
An object of the MutableString class contains the following operations/behaviors -- which means the class itself must contain the following methods:
Character charAt(int index): returns the Character at the specified index in the string -- if the index lies outside the string, throw a MutableStringIndexOutOfBoundsException (you must write this class)
void set(int index, Character ch): replaces the existing Character at the specified location -- if the index lies outside the string throw a MutableStringIndexOutOfBoundsException
void add(int index, Character ch): creates a new spot in the list for the Character at the index specified -- if the index lies outside the string throw a MutableStringIndexOutOfBoundsException
Character remove(int index): removes the Character at specified index -- if the index lies outside the string, throw a MutableStringIndexOutOfBoundsException
boolean remove(Character ch): removes the first occurrence (starting from the beginning of the MutableString) of the Character -- if the Character is not found, return false
boolean removeAll(Character ch): removes all occurrences of the specified Character -- if Character is not found, return false
void toUpper(): converts the current string to all upper case
void toLower(): converts the current string to all lower case
MutableString substring(int start, int finish): returns a string starting at the Character specified by start and concluding with the Character specified by finish -- if start or finish is outside the the string, throw a MutableStringIndexOutOfBoundsException
char [] toCharArray(): returns a char array containing all the characters in the string -- be sure and handle all cases
int length(): reports/returns the length of the string
String toString(): returns a String containing all the Characters
String toReverseString(): returns a String containing all the Characters in reverse order -- you must utilize recursion to accomplish this task
int compareTo(MutableString that): allows comparison of two MutableString objects -- this implies you will implement the Comparable interface for your MutableString class
void sort(): alphabetizes the letters in case-insensitive fashion in ascending order -- you must write the code for this sort (no API calls are allowed)
You must use a linked list to represent the characters of the string (you must write the
LinkeList class). Your LinkedList class should contain fundamental operations for updating and modifying the list. With this in mind, implement the List interface in the Java API. For methods that you deem unnecessary for your LinkedList's functionality, stub those methods out and throw an Exception that contains information about what method was called and that it has not been implemented. NOTE: Make sure your LinkedList class does not do anything MutableString specific. Feel free to use the following stubbed out LinkedList class for your assignment. It may not contain all the methods you will need, but it does contain the methods from the List interface from the Java API.
MutableString must utilize the LinkedList behaviors (methods) wherever possible (don't write code in MutableString that does the same thing as something in the LinkedList class). Thus your MutableString will contain a field that is a reference to a LinkedList object. BTW, this concept is known as delegation, a very important idea in software engineering and design. Do NOT design MutableString so that it inherits from LinkedList.
Each Node of your MutableString should contain a Character -- note that this does not mean the reference to the data in your node class should/must be type Character -- that would make your LinkedList class specific to MutableString, and we don't want that in this case.
**the part I dont understand is the paragraph 2 above that talks about inheriting from the linked list class. I was always used to writing something like public class MutableString extends LinkedList but we cant do that and I dont really know how to start writing this mutablestring class without inheriting from the class. Help on explaining how to do it and the difference would be awesome. thanks.
Im not very good at linked lists so bare with this question :)
**
It says that you should use delegation instead of inheritance.
For difference between delegation and inheritance, check this out. It explains with an example.

Resources