I have Immutable class and which has list of Mutable class objects.
class Immutable
{
final int id;
final String name;
final List<Mutable> list;
Immutable(int id,String name,List<Mutable> list)
{
this.id=id;
this.name=name;
this.list=list;
}
public List<Mutable> getMutables()
{
List<Mutable> l=new ArrayList<>(this.list);
return l;
}
}
class Mutable
{
String name;
Mutable(String name)
{
this.name=name;
}
}
Here My getMutables method is creating the objects and returning the cloned objects. But if so many threads or request access getMutables method then it will end up in creating multiple objects and soon out of memory error will come.
what to do in getMutables method so that, original Objects does not modified and more objects are not created.
Please help
Instead of returning new ArrayList in getMutables(), we can return unmodifibleList of Mutable objects from getMutables().
public List<Mutable> getMutables()
{
return Collections.unmodifiableList(this.list);
}
The unmodifiable Collection method of Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections.
Collections.unmodifiableList(mutableList);
Collections.unmodifiableSet(mutableSet);
Collections.unmodifiableMap(mutableMap);
Related
I am trying to understand C++/CLI so I can create Wrapper classes for C++ code. My problem is that I have a class which stores a pointer to a parent object of that class, therefore I need to pass it into the class.
Below is an example, but the full class has more functions and stores extra data.
class A
{
private:
A* parent;
public:
A(A* Parent)
{
parent = Parent;
}
~A()
{
delete parent;
}
A* GetParent()
{
return parent;
}
}
My current idea is to have a non-public constructor so that you can construct a managed class with the unmanaged one without it being accessible outside the class.
public ref class ManagedA
{
A* unmanaged;
ManagedA(A* unmanaged)
{
this->unmanaged = unmanaged;
}
public:
ManagedA(ManagedA^ Parent)
{
unmanaged = new A(Parent->unmanaged);
}
~ManagedA()
{
delete unmanaged;
unmanaged = NULL;
}
ManagedA^ GetParent()
{
return gcnew ManagedA(unmanaged->GetParent());
}
}
While this works for functions inside the class, I still have issues if I want to create an object or if I have a function that needs the unmanaged class to be passed in.
Is there a way I can work around this?
ManagedA^ GetParent()
{
return gcnew ManagedA(unmanaged->GetParent());
}
You are shooting your leg off with code like this, it is very dangerous. Problem is, you are creating multiple ManagedA objects that refer to the exact same A*. As soon as one of them gets destroyed, all the other ManagedA objects now have a dangling pointer. That's almost guaranteed to cause memory corruption.
The solution is very simple, just store the parent reference in the constructor:
public ref class ManagedA {
private:
A* unmanaged;
ManagedA^ parent;
public:
ManagedA(ManagedA^ Parent) : parent(Parent) {
A* unmanagedParent = Parent == nullptr ? nullptr : Parent->unmanaged;
unmanaged = new A(unmanagedParent);
}
ManagedA^ GetParent() {
return parent;
}
~ManagedA() {
this->!ManagedA();
unmanaged = NULL;
}
!ManagedA() {
delete unmanaged;
}
};
Note the added nullptr check in the constructor, the only sane way I could see how the very first A* could ever get created.
That was the easy case, the exact same object identity problem occurs when you ever need to map an A* back to a ManagedA^. First check if this is really needed, the client code is expected to only ever manipulate ManagedA objects. When necessary, you'll need to create an lookup table so you can reliably find the corresponding ManagedA^ back. That requires a static Dictionary<IntPtr, ManagedA^>. Add objects to the dictionary in the constructor, remove them in the finalizer. Note that you forgot to include a finalizer, it is not optional. I added it to the snippet.
I have a situation where the child to be able to reference the parent. The reason for this is that I want the child to have the ability to update the parent object.
configuration.Range.Next(configuration)
I do not want to pass the parent object reference instead the Range object should be able to find its parent object. How would I do this?
Class Range { ....MethodX(){How do I access the Configuration Object here } }
Class Configuration { public Range range{get;set;} ..... }
Part of the difficulty with answering your question is that people use the terms "child" and "parent" to mean different things to different people.
One of the most common uses of the terms is as synonyms for subclass (child) and superclass (parent) in an inheritance structure. Assuming that is your meaning, you already have access to anything from the superclass (i.e. "parent") that is declared as public or protected. For example:
public class Parent
{
protected int Foo { get; set; }
}
public class Child : Parent
{
public void DoSomething()
{
Foo = 42;
// or
base.Foo = 42;
}
}
If this isn't the situation you're working with please add more information to your original question to better describe what you mean when you use the terms "child" and "parent."
Is there a way to store an identifier of a model object or the model object itself in a JavaFX 2 TreeItem<String>? There is just Value to store the text...
I'm populating a TreeView from a list of model objects, and need to find it when the user clicks a node. I'm used to work with Value and Text in .NET Windows Forms or HTML and I am afraid I cannot adapt this way of thinking to JavaFX...
You can use any objects with TreeView, they just have to override toString() for presenting or extend javafx.scene.Node
E.g. for next class:
private static class MyObject {
private final String value;
public MyObject(String st) { value = st; }
public String toString() { return "MyObject{" + "value=" + value + '}'; }
}
TreeView should be created next way:
TreeView<MyObject> treeView = new TreeView<MyObject>();
TreeItem<MyObject> treeRoot = new TreeItem<MyObject>(new MyObject("Root node"));
treeView.setRoot(treeRoot);
I have the same issue as the OP. In addition I want to bind the value displayed in the TreeItem to a property of the object. This isn't complete, but I'm experimenting with the following helper class, where I'm passing in the "user object" (or item) to be referenced in the TreeItem, and a valueProperty (which, in my case, is a property of the item) to be bound to the TreeItem.value.
final class BoundTreeItem<B, T> extends TreeItem<T> {
public BoundTreeItem(B item, Property<T> valueProperty) {
this(item, valueProperty, null);
}
public BoundTreeItem(B item, Property<T> valueProperty, Node graphic) {
super(null, graphic);
itemProperty.set(item);
this.valueProperty().bindBidirectional(valueProperty);
}
public ObjectProperty<B> itemProperty() {
return itemProperty;
}
public B getItem() {
return itemProperty.get();
}
private ObjectProperty<B> itemProperty = new SimpleObjectProperty<>();
}
I have a ref class that contains a pointer to an unmanaged class. the class has some basic types and also a vector of objects of another class. I would like to know the best way to get and set the vector from managed code. Will a memcpy between unmangedb objects be efficient or setting each member variable of unmanagedb?
for ex (assume the class is complete. I am writing what is relevant to the question)
Assume we already have a managed wrapped for struct UnmanagedB called B.
struct UnmanagedA
{
int a;
vector<UnmanagedB> list;
};
public ref class A : public System::IDisposable
{
public:
// properties
property System::UInt32 a
{
System::UInt32 get();
void set(System::UInt32 value);
}
property array<B^>^ list
{
System::array<B^>^ get(); // what is the best way to set and get the vector
void set(array<B^>^ value);
}
private:
UnmanagedA* obj1;
};
This obviously won't be cleanly possible, since UnmanagedA contains a vector of UnmanagedB values, while A exposes an property of type array<B^>. If this is intended and not a typo, you will need to marshall the content of B^ into instances of UnmanagedB. Otherwise, let UnmanagedA hold a std::vector< B* > and take care of proper lifetime management.
I have a function that returns objects of different types based on the parameter passed to this function.
Is it possible to add these different object types to a collection based on some identifier in C# 4.0?
Usually we do something like this
List or List
but i want one collection which can add object of any type.
Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.
Yes, it is called object. Eg:
var objlist = new List<object>();
objlist.Add(1);
objlist.Add(true);
objlist.Add("hello");
You could use object[], List<object>, ArrayList, IEnumerable, ... but if those types have a common base type it would be better to stick to a strongly typed collection.
Really your collection should be as specific as you can make it. When you say
objects of different types
Do these objects have anything in common? Do they implement a common interface?
If so you you can specialise the list on that interface List<IMyInterface>
Otherwise List<object> will do what you want.
Update
No, not really.
I'm sorry but I'm going to question your design.
If you have a collection of different objects, how do you decide how to use one of the objects?
You're going to have a large switch statement switching on the type of the object, then you cast to a specific object and use it.
You also have have a similar switch statement in your factory method that creates the object.
One of the benefits of Object Orientation is that if you design your objects correctly then you don't need to do these large "If it's this object do this.Method(), if it's that object do that.OtherMethod()".
Can I ask, why are you putting different objects into the same collection? What's the benefit to you?
If you want a collection which can add objects of any type then List<object> is the most appropriate type.
Collections in earlier versions of C# (not generics) can contain any kind of objects. If they're value type, they will be boxed into object.
When you need to use them, you can just cast it to the original type.
You may use List<Type> to hold the type information, if that's what you want. And Type[], Hashtable, etc. are also fine. You can use typeof operator to get the type or use Object.GetType().
Also check out Dynamic type.
http://msdn.microsoft.com/en-us/library/dd264736.aspx
It will basically do the same thing.
My Suggestion:
public class ParamValue
{
object value = null;
public ParamValue(object val)
{
value = val;
}
public string AsString()
{
return value.ToString();
}
public int AsInt()
{
return int.Parse(value.ToString());
}
public int? AsNullableInt()
{
int n;
if (int.TryParse(value.ToString(), out n))
{
return n;
}
return null;
}
public bool AsBool()
{
return bool.Parse(value.ToString());
}
public bool? AsNullableBool()
{
bool b;
if (bool.TryParse(value.ToString(), out b))
{
return b;
}
return null;
}
}
public class Params
{
Dictionary<string, object> paramCol = new Dictionary<string, object>();
public void Add(string paramName, object value)
{
paramCol.Add(paramName, value);
}
public ParamValue this[string paramName]
{
get
{
object v;
if (paramCol.TryGetValue(paramName, out v))
{
return new ParamValue(v);
}
return null;
}
}
}
Use param class as a collectio to your values, you can convert the return to every type you want.
You could use a Tuple of Genric Types
public Tuple<T, T> MySuperMethod()
{
int number = 1;
string text = "Batman";
return new Tuple<int, string>(number, text);
}
The .NET Framework directly supports tuples with one to seven
elements. In addition, you can create tuples of eight or more elements
by nesting tuple objects in the Rest property of a Tuple object.
https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.100).aspx