Map.Entry next method? - hashmap

I'm looking at the source code for JDK 7 - specifically WeakHashMap.java, where there is extensive use of this:
Entry<K,V> p = prev;
Entry<K,V> next = p.next;
but next isn't a method defined on Map.Entry (as far as I can see? http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html)
Where is the call to this method coming from then?

WeakHashMap is not referring to Map.Entry, but instead, to its own internal implementation of the Map.Entry interface, a class named Entry. That class has a field named next, which it can access.

next is not a function. It is a member variable of a class that is being directly accessed. Typically you would see this (in OO code)
public class Foo
{
String bar;
public String getBar()
{
return this.bar;
}
}
The .next syntax you see is what is commonly referred to as direct member access and is typically frowned upon.

It is an inner class inside WeakHashMap, which contains a reference to Entry next:
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>{
V value;
final int hash;
Entry<K,V> next;
Entry(Object key, V value, ReferenceQueue<Object> queue, int hash, Entry<K,V> next) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
// omit others...
}
Check out the source code at line 682: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/WeakHashMap.java#WeakHashMap.Entry
This is the same thing for HashMap. It has similar inner class:
static class Entry<K, V> implements Map.Entry<K, V>

Related

Is it possible to listen for superclass property changes in Groovy?

I'd like to create an "reload" setter for a property, that I'd like to keep in a trait. Then any subclasses that implement the trait would use their own getter, but the trait's setter. I don't want to add any extra annotations to existing properties. Here's a clarification:
trait Tr {
abstract String getS()
void setS(String value) {
((GroovyObject) this).setProperty('s', value)
reloadOnSChange()
}
void reloadOnSChange() {
// do something when S is changed
}
}
class Cl implements Tr {
String s
}
Cl cl = new Cl()
cl.s = 'hello world' // reloadOnSChange should be called
Is such a property listener possible?
If you want to use trait for that then you have to do it differently than implementing void getS(String value) method, because Groovy compiler generates Cl.getS(String value) method that shadows the method implemented in the Tr trait.
Alternatively your trait can provide implementation of void setProperty(String name, Object value) method that if called for property s, it executes reloadOnSChange() method. Consider following example:
trait Tr {
abstract String getS()
abstract void setS(String s)
void reloadOnSChange() {
// do something when S is changed
println "RELOAD"
}
void setProperty(String name, Object value) {
metaClass.setProperty(this, name, value)
if (name == 's') {
reloadOnSChange()
}
}
}
class Cl implements Tr {
String s
}
Cl cl = new Cl()
cl.s = 'hello world'
println "Dump: ${cl.dump()}"
Output:
RELOAD
Dump: <Cl#6580cfdd s=hello world>
The main downside is that this setProperty method will be executed for every property, so it may generate some overhead. At some point JIT should optimize the code and make sure that this if statement is executed only when property name is equal to s.

Overriding parent methods with contravariant arguments

Basically, I want to override a parent class with different arguments. For example:
class Hold<T> {
public var value:T;
public function new(value:T) {
set(value);
}
public function set(value:T) {
this.value = value;
}
}
Then override that class, something like:
class HoldMore extends Hold<T> {
public var value2:T;
public function new(value:T, value2:T) {
super(value);
set(value, value2);
}
override public function set(value:T, value2:T) {
this.value = value;
this.value2 = value2;
}
}
Obviously this will return an error, Field set overloads parent class with different or incomplete type. Is there a way around this? I tried using a public dynamic function, and then setting set in the new() function, but that gave a very similar error. Any thoughts?
This is just a complement to #stroncium's answer, which is totally correct.
Here is an example how it could look like:
class Hold<T> {
public var value:T;
public function new(value:T) {
set(value);
}
public function set(value:T) {
this.value = value;
}
}
class HoldMore<T> extends Hold<T> {
public var value2:T;
public function new(value:T, value2:T) {
super(value);
setBoth(value, value2);
}
// you cannot override "set" with a different signature
public function setBoth(value:T, value2:T) {
this.value = value;
this.value2 = value2;
}
}
alternatively, you could use an array as parameter or a dynamic object holding multiple values in order to "set" them using the same method, but you loose some of the compiler's type checking.
If you wrote the base class you could add an optional argument to it, this would be a workaround though, not directly what you want to do.
In the current state it totally won't work. There is not only 1 problem, but few of them:
Type T is meaningless in context of this new class, you should either use some concrete type or template this class over T.
You can not change the number of arguments of function when overriding it. However you can add another function(with a different name) to accept 2 arguments and do what you want (which is the way you would use in most languages, by the way).
I don't really understand how you see a contravariance problem there. The actual problem is that haxe doesn't support function overload. (It actually does, the function signature is name + full type, but that's not what you would want to write nor support, and is mostly used for js/java externs.)
Unfortunately the language doesn't allow it.

Change struct values from a different class

I am trying to change a struct values (located in class A) from another class (class B per say) I wrote a method to get the struct (the method is located in class A) but all I get is a shallow copy (the values do not really change...) any help?
Yes, that's what happens with structs. You need to make the changes locally, then shallow copy back again. For example:
public class Foo
{
public Point Location { get; set; }
}
public class Bar
{
private Foo foo = new Foo();
public void MoveFoo()
{
Point location = foo.Location;
location.X += 10;
location.Y += 20;
// Copy it back
foo.Location = location;
}
}
Personally I try to avoid making structs mutable in the first place - but will often given them what I call "pseudo-mutator" methods which return a new value with appropriate changes. So for example, for a Point struct I might have a method like this:
public Point TranslatedBy(int dx, int dy)
{
return new Point(x + dx, y + dy);
}
Then the MoveFoo method above would be:
foo.Location = foo.Location.TranslatedBy(10, 20);

groovy: variable scope in closures in the super class (MissingPropertyException)

I have the impression that closures run as the actual class being called (instead of the implementing super class) and thus break when some variables are not visible (e.g. private in the super class).
For example
package comp.ds.GenericTest2
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
this.add(obj)
}
}
b = new ClosureScopeD()
// THIS THROWS groovy.lang.MissingPropertyException: No such property: accessThisPrivateVariable for class: comp.ds.GenericTest2.ClosureScopeD
b.doSomething("abc")
The last line throws a MissingPropertyException: the child class calls the "add" method of the super class, which executes the "each" closure, which uses the "accessThisPrivateVariable".
I am new to groovy, so I think there must be an easy way to do this, because otherwise it seems that closures completely break the encapsulation of the private implementation done in the super class ... this seems to be a very common need (super class implementation referencing its own private variables)
I am using groovy 2.1.3
I found this to be a good reference describing how Groovy variable scopes work and applies to your situation: Closure in groovy cannot use private field when called from extending class
From the above link, I realized that since you have declared accessThisPrivateVariable as private, Groovy would not auto-generate a getter/setter for the variable. Remember, even in Java, private variables are not accessible directly by sub-classes.
Changing your code to explicitly add the getter/setters, solved the issue:
package com.test
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
int getAccessThisPrivateVariable() { accessThisPrivateVariable }
void setAccessThisPrivateVariable(int value ){this.accessThisPrivateVariable = value}
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
super.add(obj)
}
}
b = new ClosureScopeD()
b.doSomething("abc")
There is a simpler way, just make the access modifier (should rename the property really) to protected, so the sub-class has access to the property.. problem solved.
protected int accessThisProtectedVariable
To clarify on your statement of concern that Groovy possibly has broken encapsulation: rest assured it hasn't.
By declaring a field as private, Groovy is preserving encapsulation by intentionally suspending automatic generation of the public getter/setter. Once private, you are now responsible and in full control of how or if there is a way for sub-classes (protected) or all classes of objects (public) to gain access to the field by explicitly adding methods - if that makes sense.
Remember that by convention, Groovy ALWAYS calls a getter or setter when your codes references the field. So, a statement like:
def f = obj.someField
will actually invoke the obj.getSomeField() method.
Likewise:
obj.someField = 5
will invoke the obj.setSomeField(5) method.

Retrieving an Enum through a class and its descendants

I have a class that I've defined, and I have a number of child classes derived from it. The parent class has an enum (let's call it 'Barf'). Each descendant ALSO has an enum with the same name but not the same values. What I'm trying to figure out how to do is write a method in the ancestor class that gets the version of Barf for the actual class of the instantiated object. So if I create an instance of Ancestor, I'd like to have this method process the entries for Ancestor.Barf . If I create an instance of one of the child classes of Ancestor, I'd like to have the method process Childx.Barf values.
Obviously this is going to be a Reflection solution, but my reflection skills are pretty sparse. Any help?
Just for the fun of it, here is a possible approach:
public class Ancestor {
public enum Caffeine {
Tea,
Coffee
}
public void ProcessValues() {
var type = GetType();
var nestedEnums = from t in type.GetNestedTypes()
where t.IsEnum
select t;
var nestedEnum = nestedEnums.Single();
foreach(var val in Enum.GetValues(nestedEnum)) {
Console.WriteLine("Drinking {0}", val);
}
}
}
public class Descendant : Ancestor {
public new enum Caffeine {
Jolt,
RedBull
}
}
// The following prints:
// Drinking Jolt
// Drinking RedBull
Ancestor x = new Descendant();
x.ProcessValues();
Of course, you could achieve the same thing using polymorphism:
public class Ancestor {
public enum Caffeine {
Tea,
Coffee
}
protected virtual Type GetNestedEnum() {
return typeof(Ancestor.Caffeine);
}
public void ProcessValues() {
var nestedEnum = GetNestedEnum();
foreach(var val in Enum.GetValues(nestedEnum)) {
Console.WriteLine("Drinking {0}", val);
}
}
}
public class Descendant : Ancestor {
public new enum Caffeine {
Jolt,
RedBull
}
protected override Type GetNestedEnum() {
return typeof(Descendant.Caffeine);
}
}
As Justin Morgan has pointed out however, having the need for such a construct may be an indication of an underlying design issue in your code.

Resources