initialise variable from another variable type - java

I have the class which have the variable and method as below:
public class ProjectsPage extends State {
private Container<Project> newcontainer;
public ProjectsPage(Kick kick) {
super(kick);
}
public void setItem() {
newcontainer = ??? kick.proj
}
}
Object kick has variable proj with the same type as newcontainer:
public class Kick {
public Container<Project> proj = new ContainerDB();
//here I add content to proj
}
Now I want to initialise newcontainer with the same constructor ContainerDB as kick.proj. In another words make an empty kick.proj. Something like this (since kick.proj and newcontainer uses the same interface):
newcontainer = new ContainerDB();
But the problem is class kick can change classes for proj.Like
public class Kick {
public Container<Project> proj = new ContainerDBSQL();
//here I add content to proj
}
I need it (I mean initialise with the same type) since newcontainer later on should contain only specific entries from kick.proj. Not all entries.
How to do it?

try instantiating the object with this:
newContainer = kick.proj.getClass().newInstance();

Related

"Creator" pattern to configure inherited objects

I have the following object structure:
class Annotation;
class LabelAnnotation: inherits Annotation;
class TextAnnotation: inherits LabelAnnotation;
I would like to use "creator" objects to do some initialization on these object (This initialization depends on external settings so I don't want to do it in the constructor of these objects.)
In particular, when creating a LabelAnnotation I would like to do:
fontSize = AppDefaults.fontSize
So I'm writing a "creator":
class LabelAnnotationCreator {
LabelAnnotation create() {
annotation = LabelAnnotation()
annotation.fontSize = AppDefaults.fontSize
return annotation;
}
}
Now, I would like to create a TextAnnotationCreator. This is where I'm stuck: I can't use the LabelAnnotationCreator because it would create an instance of a LabelAnnotation, but on the other hand, I want to benefit from the initialization performed by the LabelAnnotationCreator.
class TextAnnotationCreator {
TextAnnotation create() {
annotation = TextAnnotation()
// I'm stuck here:
// can't do LabelAnnotationCreator().create()… ???
return annotation;
}
}
Obviously, this isn't the right pattern but I'm not sure how to find the correct one.
Thanks!
what do you think about this:
class TextAnnotation {
private final int someOtherArgs;
private final int fontSize;
public TextAnnotation(LabelAnnotation labelAnnotation, int someOtherArgs) {
this(someOtherArgs, labelAnnotation.getFontSize());
}
public TextAnnotation(int someOtherArgs, int fontSize) {
this.someOtherArgs= someOtherArgs;
this.fontSize = fontSize;
}
}
create a constructor on TextAnnotation that builds a object from a LabelAnnotation configuration. Then you can use it like this:
TextAnnotation text = new TextAnnotation(someArgs,fontSize);
or using your creator
class TextAnnotationCreator {
TextAnnotation create() {
return
new TextAnnotation(
new LabelAnnotationCreator().create(),
someOtherArgs
);
}
}

How can I assign instance of a class from an array to a class initializer in java?

In a Android application I am making I have an array of instances of a certain class I made, and later in the program I need to use the getter and setter methods from that class on an instance of the class from the array. Do I need to assign the instance of the class from the array to a new class initializer? Here is some code to clear this up:
Class
public class ProfileInformation {
private String console;
private String gamertag;
public String getConsole() {
return console;
}
public void setConsole(String console) {
this.console = console;
}
public String getGamertag() {
return gamertag;
}
public void setGamertag(String gamertag) {
this.gamertag = gamertag;
}
}
Array
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
Some instances of ProfileInformation are then added to arraylist, and then I get one of the instances from the arraylist and try to use getGamertag() to set it to a string:
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
The problem is example will equal null. Why is this?
First, an Arraylist is a List, try not to confuse that with actual arrays.
Do I need to assign the instance of the class from the array to a new class initializer?
You don't need to get an element out of the Arraylist, no. You can chain many methods together
String example = ProfTags.get(ProfTags.size()-1).getGamertag();
example will equal null. Why is this?
For the same reason any object is null... You never set it equal to anything else
This code runs on my laptop:
public static void main(String[] args) {
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
element = new ProfileInformation();
element.setGamertag("Actual Gamer tag value");
ProfTags.add(element);
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
}
Output is:
Actual Gamer tag value
I guess you didn't call setGamertag(String).

Java - Set capable of referencing instances of a different class

Can anyone help me with this java code?
I have two classes and need to create a set that can store instances of the other class. here is the sample I managed to "commit" :)
Class A
public Class Rabbit {
private String age;
//constructor for instance of Rabbit <br>
public Rabbit(String rabAge) {
super();
this.age = rabAge;
}
now class B:
public class ManyRabbits {
private Set <String> setOfRabbits;
now this method should create a new instance of the Rabbit and add it to the set represented by variable setOfRabbits
public void addRabbit (String age)` {
//and I don't know what should go next...something like: `
Rabbit r1 = new Rabbit("10");` <br>
setOfRabbits.add(r1);
}
You need to change your set declatation :
private Set<Rabbit> setOfRabbits;
And you also need to ovweride those two method in order to never insert twice the same object in the set.
#Override
public int hashCode() {
// Your own implementation
return ...;
}
#Override
public boolean equals(Object o) {
// Your own implementation
return ...;
}
your ManyRabbits calss should be like this
public class ManyRabbits
{
private Set<Rabbit> setOfRabbits = new HashSet<Rabbit>();
public void addRabbit (String age)
{
Rabbit r1 = new Rabbit(age);
setOfRabbits.add(r1);
}
}
public class Rabbit {
private String age;
//constructor for instance of Rabbit
public Rabbit(String rabAge) {
super();
this.age = rabAge;
}
// more methods if necessary
}
In ManyRabbits:
public class ManyRabbits {
private Set <Rabbit> setOfRabbits = new HashSet<>();
public void addRabbit (String age) {
Rabbit r1 = new Rabbit(age);
setOfRabbits.add(r1);
}
// more methods if necessary
}
Use it by calling something like
ManyRabbits manyRabbits = new ManyRabbits();
manyRabbits.addRabbit("10");
manyRabbits.addRabbit("20");
manyRabbits.addRabbit("30");
Say:
Set<Rabbit> setOfRabbits = new HashSet<>();
setOfRabbits.add(new Rabbit());
When the Set will be keeping track of an unknown quantity of an object, I typically try to instantiate with an unnamed instance. This would work great for adding to a listener so that you could, say, add a new Rabbit every time the user clicks.
In this way, you could add however many Rabbit object you want. Try:
for(i = 0; i < 10; i++) {
setOfRabbits.add(new Rabbit());
}
You may see this in older versions of Java:
Set<Rabbit> setOfRabbits = new HashSet<Rabbit>();
but it is no longer necessary

Manipulating an object inside a method

I am trying to manipulate an object inside a method like this:
My class Problem:
public class TaxiProblem {
public Problem(final World world, final Agent agent) {
_world = world;
_world.setRandomAgent(_agentPlace);
}
private Place _agentPlace;
// Various other functions
}
and in the function .setRandomAgent() in the class World I am trying to manipulate the Place object in what I want it to be like this:
public void setRandomAgent(Place agentPlace) {
int rand = _random.nextInt(25);
agentPlace = _places.get(rand);
agentPlace.setHasAgent(true);
}
I basically want to grab a random Place from the List _places and have it in the variable agentPlace in .setRandomAgent() which in turn will have it in _agentPlace in the Problem class. I thought this would work since Java passes objects by reference in methods but it didn't and _agentPlace remains null.
By doing this
agentPlace = _places.get(rand);
you are overwriting the reference that was passed to the method and losing access to the object you want to alter.
In your setRandomAgent method, agentPlace is indeed a reference that points to your _agentPlace field, not the field itself. In the line I pasted above, what you do is make that reference point to a different object.
_agentPlace = _world.getRandomAgent();
public Place getRandomAgent() {
int rand = _random.nextInt(25);
Place agentPlace = _places.get(rand);
agentPlace.setHasAgent(true);
return agentPlace();
}
When you pass agentPlace to the method, you are creating a copy of the reference. So if you modify the object, then it would work when you return up the stack. But reassigning the variable makes you lose the object you were working with.
I suspect that your problem lies in the implementations as your understanding of pass by reference I believe is correct. The following code will produce the results you expect - That is, it will first print "Before change", then "I am changed!".
class Program
{
static void Main(string[] args)
{
var problem = new Problem();
}
}
public class Problem
{
public Problem()
{
var toChange = new ClassToChange();
toChange.ChangeMe = "Before change";
Console.WriteLine(toChange.ChangeMe);
var changer = new ClassThatChanges();
changer.ChangeSomething(toChange);
Console.WriteLine(toChange.ChangeMe);
Console.ReadLine();
}
}
public class ClassToChange
{
public string ChangeMe { get; set; }
}
public class ClassThatChanges
{
public void ChangeSomething(ClassToChange classToChange)
{
classToChange.ChangeMe = "I am changed!";
}
}

Remove key and value from object

My data model is as follow:
public class CustomerObject implements Serializable
{
public Integer pkid;
public String code;
public String name;
public CustomerObject()
{
pkid = new Integer(0);
code = "";
name = "";
}
}
Now I am calling this from another class:
public CustomerObject getCustObj() {
CustomerObject custObj = new CustomerObject();
custObj.pkid = new Integer(1001);
custObj.code = "CUST1001";
return custObj;
}
Now here in getCustObj() function I want to pass only pkid and code. I mean I want to remove the variable "name" from the object and then pass. So my passing object will look like:
CustomerObject()
{
pkid = 1000;
code = CUST1001;
}
Please help how I can do this.
Actually I have a data model of 200 variable. I will pass this using webservice. But during pass by webservice I may need only 20 to pass. So I want to reduce the data size.
Use another constructor in class CustomerObject as following.
public class CustomerObject implements Serializable
{
public Integer pkid;
public String code;
public String name;
public CustomerObject()
{
pkid = new Integer(0);
code = "";
name = "";
}
public CustomerObject(int inPkid, String inCode)
{
this.pkid = inPkid;
code = inCode;
}
}
When you call getCustomerObject method from another class use as follows
public CustomerObject getCustObj() {
CustomerObject custObj = new CustomerObject(new Integer(1001),"CUST1001");
}
If you are not setting name in your object, then it is as good as object not having name because name is null. You can't remove name variable from the object.
But if you really want to do so, you can use inheritance. Make one class with all attributes except name and other class extends the first class and adds name attribute to it. So now you can use first class when you don't need the name attribute.

Categories