Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm new to Java, and get really confused about deep copy.
I think each method that takes some mutable objects as arguments and returns an object that is related to the input should make defensive copy. However, after some coding I find this is very tricky.
For example, I want to choose some objects from a container satisfying some conditions, and returns them as a smaller container:
List<SomeType> chooseWithSomeCondition(List<SomeType> input)
But SomeType is defined by others, which is not immutable, not clonable, not serializable, neither has any copy constructor. Since Java's final cannot help either, I don't know how to make deep copy here.
Is my criteria too strict? Is the code I've read problematic? Are there some other ways to make deep copy? Please share your thoughts, and thanks in advance.
In this particular case, the code is problematic, and I'd just do a shallow copy. In your docs, note that the method is actually "chooseWithSomeConditionAtThisInstant" and tell others NOT to modify the elements of either list, or to do so with care and thought. (There are use cases where you want changes to come through.)
In the case of a type where you cannot use normal copying methods for deep copy (in your case of non-serializable, non-clonable, non-instantiable...), you would need to work around with reflection.
If you think reflection is too slow, or constructors can't be used, then you may want to think about using sun.misc.Unsafe to instantiate.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Currently my program is filled with many ugly references that often make field or method access look like this: weakReference1.get().weakReference2.get().field1.getSomeCustomObject().field2. I want to move to shorter and faster strong references like field1.field2. But my program design is such that I will also have to go for an ArrayList element-by-element search (in a for-loop) instead of accessing a WeakHashMap by get() method.
Thus, I'd like to understand, can moving to simpler references compensate for rejecting HashMap performance wise. Herewith I presume that WeakHashMap.get() is much faster than a loop-search of ArrayList.
Can someone, please, give me a rough estimate? Or maybe there's even an appropriate comparison table like this one. I'd appreciate that.
Thank you.
Currently my program is filled with many ugly references that often make field or method access look like this:
weakReference1.get().weakReference2.get().field1.getSomeCustomObject().field2
Given that the objects involved are not Data Transfer Objects
this is a violation of the law of Demeter aka Don't talk to Strangers / Tell, don't ask!
Following this LoD principle you should move the operations working with the data in field2 to a new method in the class SomeCustomObject.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I was using this code to create some sort of a universal changer class:
//constructor method
public Change(Object affdObj, String affdField, float modifier) {
obj = affdObj;
//...
affectedField = affdObj.getClass().getField(affdField);
//...
affectedField.setFloat(obj, affectedField.getFloat(obj) + modifier);
}
But then I was advised to avoid reflection whenever possible since it's very slow. I was suggested to pay attention to interfaces. Unfortunately I can't see how to fit interfaces to my code.
Hence my question: if one needs to access a field which name he doesn't know in advance are there any options other than using reflection?
PS
Thank you for replies, guys.
And since my question is put on hold as primarily opinion-based, I consider this to be the answer to my question, i.e. there is no other way to achieve my goal which is better than mine in every aspect. In other words, I conclude that my approach is OK. Thank you.
First of all, reflection is not slow (anymore) and is widely used (Spring uses it, Hibernate uses it, etc.). So, you use it with confidence if your only concern is speed.
Regarding other ways to do what you want, since you provide the field name as as a string and identify it like that, you cannot do it with interfaces.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm using Java to do some complicated calculations, and have a lot of classes that need access to a lot of the same variables. These variables are set at different stages of the calculations, in different classes. The problem is that my code is getting quite messy as I am being forced to pass the same parameters to a lot of different methods.
I am looking for peoples thoughts on what the best approach here would be? One idea I have is to make a superclass with all these variables set in it and extend this class everywhere it is needed.
Another option is to pass an object holding all this information around from method to method but this seems overly complex.
Neither of these solutions feel like the cleanest approach to me. Any thoughts or suggestions of design patterns/ideas that may help me are appreciated. Thanks for your help.
I'm going to suggest that using a Wrapper object is the best way to do this. Make sure all fields are immutable (final keyword in Java). Use a Builder or Prototype pattern to create new objects to return.
How about using a Singleton? That way you'd have global access to it without passing any instances around and all the variables will be under one roof reducing messiness.
I would recommand to separate the problem world (i.e. the variables) from the algorithms (i.e. calculations) in separate classes. The algorithms would get passed in the problem world, and modify it accordingly. This can be seen as an implementation of the Visitor Pattern.
Depending on the complexity (number of variables, number of algorithms, uncernity of solution path), you could also implement a Black Board Architecture. But I think that would be an overkill, if you're not doing something in artificial intelligence...
If there are a lot of values to be passed around, perhaps an in-memory database would be an appropriate solution. A lot of databases these days offer an in-memory engine, e.g. MariaDB.
Make a superclass of subclasses then refer to those subclasses of the superclass everytime you need to pull information
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am currently working on an uni assignment. We have to write Javadoc comments. My problem is that I don't really know to whom I'm "talking" here.
Some examples for comments to different methods in my project:
"The next thing we care about is the number of..."
"We want to remove those items from the list because..."
So the questions is: can i put Javadocs like that or do I have to write them in formal language? And who do I adress in my sentences (if I can adress someone).
It's entirely up to you / your team how formal or informal to make your Javadoc.
It's relatively rare to directly address anyone (either with "you" or "we"), but again, it's your call. Consider the JDK's docs, which typically go something like this:
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Direct, clear, and impersonal. Just state the facts.
Another example (from Object#equals):
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Notice how it didn't say "Note that you must generally override..." It doesn't tell anyone what to do, just notes that if doing X, generally it's necessary to do Y.
Javadocs matter most if you're publishing to third parties. You won't be present to expound on your code. Third parties will want to just use your classes wo/ worrying about how they fulfill their contract. Your documentation should tell them what they need to know: what the terms of the contract is. They need to know what to provide, what to expect back, exceptions, invariants, etc.
I would say keep the language formal in that case. It reflects better on you.
You don't communicate with third parties the same way you do your friends. Better to keep it formal.
I would stop using "we" and think more in terms of "you". It's about the consumer of your library, not the developers.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to add software enforced copy-on-write for multithreaded applications in Java? By this I mean threads having a reference to the same object, but when one thread attempts to modify it, the object pointed to is copied and the reference is adjusted to point to that copy.
The only implementation I know is the
java.util.concurrent.CopyOnWriteArrayList
see
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html
and the related Set class
java.util.concurrent.CopyOnWriteArraySet
and finally
org.apache.mina.util.CopyOnWriteMap
but it depends from your need.
If your question is,
is it possible to enforce copy-on-write behavior across the board for an entire Java runtime
then the answer is,
No, there is no such general capability in Java.
Actually, I think the closest you can possibly get to that goal is using Clojure. All its default data structures are copy-on-write internally, and on the outside they are simply immutable objects.
The references you talk about are called, surprisingly, refs and they support full in-memory transactions. A simpler kind of a reference is atom, which fits your description 100%.
The whole Core API is devoted to elegant and epressive manipulation of these structures in a thread-safe, lock-free manner.
Yes. Lazy copying is easy to implement, but you would generally have to do it yourself.