This is a simple question (I think)
Lets say I have this code (Assuming I have a dog class)
String name = "dog";
dog name = new dog();
How can I get java to recognize name as a String and name the object dog?
While you can do what you're trying in some scripting languages such as PHP (and this question is often asked by many PHP programmers who start Java), this is not how Java works, and in fact variable names are a much less important than you may realize and hardly even exist after code is compiled. What is much more important and what is key are variable references -- the ability to gain access to a particular object at a particular point in your program, and you can have Strings refer to objects easily by using a Map as one way.
For example
Map<String, Dog> dogMap = new HashMap<String, Dog>();
dogMap.put("Fido", new Dog("Fido"));
Dog myPet = dogMap.get("Fido");
Or you can gain references to objects in many other ways such as via arrays, ArrayLists, LinkedLists, or several other collectinos.
Edit
You state:
The thing is that in my code I am going to be using one method to create objects, the name of the object is arbitrary but I need it to be dynamic because it wont be temporary, so the actually name of the object has to change or I will be writing over the previously declared object.
This is exactly what I meant when I said that the name of the variable is not as important as you think it is. The variable name is not the "object name" (this really doesn't exist in fact).
For example if you create a dog in a variable named Fido, and then assign it to a new variable named spot, both variables, despite having different names will refer to the very same object:
Dog fido = new Dog;
Dog spot = fido; // now fido and spot refer to the same object
If you want to give a variable a "name" consider giving the class a name property:
class Dog {
private String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Now you can give each Dog object its own (semi) unique name if you wish.
I don't suppose you are thinking of Enums?
private static void test () {
Animal animal = Animal.valueOf("Dog");
}
enum Animal {
Dog,
Cat,
Cow,
Pig,
Rat,
Ant,
Gnu;
}
Related
I'm currently sitting at an exercise, which wants me to create a Java program based on an already finished documentation HTML sheet.
For example, one entry states
reversedArray
public static Object[] reversedArray(Object[] array)
Based on the name, we can assume the method should return an array in the reversed order of array.
Now my question isn't about how to create the said array, but more about the Object[] terminology. What does it mean? Should I create a bunch of methods through overloading each with a specific array type (e.g. String[], int[], ...) or literally an Object[]?
It's the latter, how does an object array work? Based on the name, I assume it's an array that can hold objects, but I'm unsure what this means in practice.
Object[] is basically just an array of objects (best explanation award right here please ----> ☐ )
Jokes aside, in Java, any object is derived from the class Object so basically, this array can store any object of any class. It's mostly useful when you just want to carry an instance (or several instances) of different classes, but the type of said instance is not important.
Let's say you have multiple classes that are not necessarily related :
Class Dog {
String name;
public Dog(String name) {
this.name = name
}
public String toString() {
return "Hello! I am a dog called " + this.name;
}
}
Class Refrigerator {
public Refrigerator() {
}
public String toString() {
return "I am a refrigerator";
}
}
Since both classes are implicitly derived from Object and that Object implements the method toString() you can override that method in both of you class declarations.
Then you can store any instance of these in a Object and call the method toString(), like so :
Dog myDog = new Dog("Spike");
Object anyObject = myDog;
System.out.println(anyObject.toString()); //would print the result of your "toString()" method in the Dog class :
//"Hello! I am a dog called Spike"
Refrigerator myFridge = new Refrigerator();
Object secondObject = myFridge;
System.out.println(secondObject.toString()); //would print the result of your "toString()" method in the Refrigerator class :
//"I am a refrigerator"
This allows you to create a method that accepts any object and treats them the same and assign any object in argument :
public void printWhatYouAre(Object o) {
System.out.println(o.toString());
}
public void doingSomething() {
Dog myDog = new Dog("Spike");
Refrigerator myFridge = new Refrigerator();
printWhatYouAre(myDog);
printWhatYouAre(myFridge); //would print the same as above
}
In your case, your method only needs to rearrange an array, which means it doesn't even need the method toString nor does it need to know what the objects are. It just needs to store an array of something into an other array of something in a different order.
Here is a nice reading about polymorphism in Java, which is basically applicable in any language, but the examples that are used are wrote in Java. The whole site actually is a pretty good reference, so it's worth taking a look, especially the OOP sections which are the most related to your post. ;)
As the name already states, the method should create a new array in
the reversed order of "array".
The method name only says to "reverse" the array; whether it's just a matter of modifying the actually supplied array or constructing a new one is something you'll need to clarify with the author of the requirement if it's not clear.
Now my question isn't about how to create said array, but more about
the "Object[]" terminology. Basically, I'm unsure what to do. Does
said "Object[]" mean, I should create a bunch of methods through
overloading each with a specific array type (e.g. String[], int[],...)
or literally an Object[] array?
No, you only have to create overloads for the primitive types i.e. int[], long[] etc and that's only if your requirement says so. the aforementioned method should be able to consume Object[], String[] , Integer[] , Double[] etc...
It it's the latter, how does an object array work? Based on the name I
assume, it's an array that can hold objects, but I'm unsure what this
means in practice.
The method name has nothing to do with what an array can hold, the method argument is an array of Object's and it's as simple as that.
Reading you might find useful:
Arrays
This is a simple question (I think)
Lets say I have this code (Assuming I have a dog class)
String name = "dog";
dog name = new dog();
How can I get java to recognize name as a String and name the object dog?
While you can do what you're trying in some scripting languages such as PHP (and this question is often asked by many PHP programmers who start Java), this is not how Java works, and in fact variable names are a much less important than you may realize and hardly even exist after code is compiled. What is much more important and what is key are variable references -- the ability to gain access to a particular object at a particular point in your program, and you can have Strings refer to objects easily by using a Map as one way.
For example
Map<String, Dog> dogMap = new HashMap<String, Dog>();
dogMap.put("Fido", new Dog("Fido"));
Dog myPet = dogMap.get("Fido");
Or you can gain references to objects in many other ways such as via arrays, ArrayLists, LinkedLists, or several other collectinos.
Edit
You state:
The thing is that in my code I am going to be using one method to create objects, the name of the object is arbitrary but I need it to be dynamic because it wont be temporary, so the actually name of the object has to change or I will be writing over the previously declared object.
This is exactly what I meant when I said that the name of the variable is not as important as you think it is. The variable name is not the "object name" (this really doesn't exist in fact).
For example if you create a dog in a variable named Fido, and then assign it to a new variable named spot, both variables, despite having different names will refer to the very same object:
Dog fido = new Dog;
Dog spot = fido; // now fido and spot refer to the same object
If you want to give a variable a "name" consider giving the class a name property:
class Dog {
private String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Now you can give each Dog object its own (semi) unique name if you wish.
I don't suppose you are thinking of Enums?
private static void test () {
Animal animal = Animal.valueOf("Dog");
}
enum Animal {
Dog,
Cat,
Cow,
Pig,
Rat,
Ant,
Gnu;
}
I have a Model class defined in my project. and as usual it has some private variables and public getters and setters
public class Person{
private ArrayList<String> mark;
public void setMark(ArrayList<String> mark){
this.mark = mark;
}
public void getMark(){
return this.mark;
}
}
Suppose in some other class I am using this Model like
Person person = new Person();
ArrayList<String> mark = new ArrayList();
mark.add("10");
mark.add("15");
mark.add("18");
person.setMark();
then the private variable of person holds the value "my name", the I am accessing the variable using public getter of the class like
ArrayList<String> localMark = person.getMark()
so as per my knowledge person.getMark() returns the reference of private variable name, so if I modify the local variable 'localMark', then it will effect the private variable of Person class, so there it breaks the private property of the variable
ex:
ArrayList<String> localMark = person.getMark();
System.out.println(localMark.get(0)); // will be "10"
localMark.set(0,"25") // person.mark will be changed
System.out.println(person.getMark().get(0)); //will be printing "25"
most of the developers following the same design pattern I guess, but what is the correct way to create Models
EDIT
As per the comment of vinod I checked, and Strings it passes value but not reference but for ArrayList... it returns reference.
You have a reference (name) to an object instance (the value of name). As the reference is private, you're in full control of it.
When you return a reference, you in fact return it 'by value', meaning that a copy of the reference is returned. Both references point to the same value (the String instance)).
An outside caller obtaining the reference can assign a new value, but your model's own reference is unaffected by that and still points to the value.
It's like a dog (object) on a leash (reference).
When you return a reference you're returning a new leash onto the same dog.
The owner of the new reference can modify your dog (pet it, shave it, whatever) when the dog is mutable (which Strings are not, so it cannot be modified)
...or he can attach a new dog to his leash
...but he can never (reflection aside) attach YOUR leach to another dog.
If the instance being exposed by call to get() is mutable, then whatever changes you make in some other place will be reflected in the instance everywhere it is used.
Example :
methodX classA -
List<String> locaNamesList = person.getNamesList();
locaNamesList.clear();
Somewhere else
methodY classB -
List<String> locaNamesList = person.getNamesList(); // note the same person instance should be used.
//locaNamesList will be empty here
Just re-assigning the reference won' change anything.
List<String> locaNamesList = person.getNamesList();
locaNamesList = null; // won't change the actual list. You are setting local field locaNamesList to null and not the actual instance.
You have to use defensive-copies of mutable instances and pass them around if you don't want the original instance to be changed by external players (provided you can't make the instance itself immutable)
I am creating a vector which stores the object of a particular class.
This class a String variable which is the identifier of that object.
So, I create an object and set this variable as "abc". Then after this object is destroyed I make another object and set the same variable as "abc".
Now I have to check if there is any object in vector already present with variable set as "abc".
I have tried using toString() and comparable() as such but no success.
I know I can make a loop and check for it but I was hoping for some simpler and faster way.
Thanks in advance.
Do you mean something like…
We have a class Dog.
public class Dog {
public String name;
public String color;
public ZonedDateTime dateOfBirth;
public Dog( String nameArg ) {
this.name = nameArg;
}
}
We collect instances in a Vector.
Vector dogs = new Vector( 3 );
dogs.add( new Dog( "Jupiter" ) ) ;
dogs.add( new Dog( "Jasmine" ) ) ;
dogs.add( new Dog( "Jacques" ) ) ;
Later we want to test if the Vector contains any dog by the name of "Jasmine"? Not that particular dog above, but any containing that text as its name?
Yes, looping to ask each dog's name and compare the text returned is one way.
Another way is to override the equals method to compare names. Then you can call the contains method on the vector to see if it has a matching dog object. But overriding equals is often not realistic. In this example, sharing a name does not mean we have the same dog and so we don't want that to be the definition of equals.
Map
A better approach is to use a different collection than Vector. One of the Map implementations makes more sense. A map stores a pair of objects, a key and a value.
In this example the dog's name string would be the key. The dog object would be the value. When you later provide the key, you can retrieve the value (the dog object). You can ask the map if it contains contains a particular key.
See the Tutorial on Map.
By the way, Vector is generally not used any more. It was long ago supplanted by other implementations of List such as ArrayList and LinkedList.
I am totally confused with ArrayList behavior. Wrote really long post, then realized no one is going to analyse huge code, so just core of the problem. Numbers are for convenience, but in my app these 0 and 24 are dynamic values.
ArrayList<VoipBlock> sortedBlocks = new ArrayList<VoipBlock>();
VoipBlock vb3 =new VoipBlock();
vb3=sortedBlocks.get(0);
vb3.setPacketNumber(24);
Essentially my final aim is to: modify and add back to arrayList as new value. However when I do that the guy at position 0 in ArrayList -> unsortedBlocks.get(0); replicates all the changes done to vb3 which of course is not what I want. I want vb3 acquire same values as VoipBlock inside of ArrayList, but I want it to be detached.
This is yet another case of passing by reference. I hate technical explanations - Java passes everything by value, BUT in some cases it passes references by values - this is same as saying not-oily oil. Please help.
It reminds me my start of learning JavaScript - I hated the language - until I watched proper materials at lynda.com - JavaScript Good Practices? - Diagrams killed me. It is the lazy description that turns us-youth away from brilliant technology, not the technology itself.
Please don't let it bother my stress and don't be in any way offended by me, it is just general complaining, maybe someone will look at it and make life better :-)
Thanks for Your time,
Desperately awaiting for help :-)
To achieve your objective you can use clone method. you have to override this method in VoipBlock class
Lets say VoipBlock is as follows
public class VoipBlock {
private int packetNumber;
private String type;
public int getPacketNumber() {
return packetNumber;
}
public String getType() {
return type;
}
public void setPacketNumber(int value) {
packetNumber = value;
}
public void setType(String value) {
type = value
}
public VoipBlock clone() {
VoipBlock clone = VoipBlock();
clone.setType(this.getType());
clone.setPacketNumber(this.getPacketNumber());
return clone;
}
}
So, using the same code you can do like as follows
ArrayList<VoipBlock> sortedBlocks = new ArrayList<VoipBlock>();
VoipBlock vb3 =new VoipBlock();
sortedBlocks.add(vb3);
vb3=sortedBlocks.get(0).clone();
vb3.setPacketNumber(24);
Note that upon calling clone method in above code segment, vb3 get assigned with a new VoipBlock instance. And already inserted VoipBlock to the array remains unchanged.
if you are looking to have kind of sample instances of VoipBlock instances which you later wanted to use in creating similar instances like them. check on immutability/mutability aspect of the code. check "Effective Java" by Joshua Blouch
The following will always copy the reference of b to a:
AnyClass a = ...;
AnyClass b = ...;
a = b;
What you want is probably to clone the object:
a = b.clone();
If I understand correctly, you're a bit unsure about how references and values work. I think the rule of thumb is that primitive types like int, char, boolean and maybe String are copied but Objects just have their reference passed.
The line vb3=sortedBlocks.get(0); completely replaces whatever vb3 used to be with the first thing in the ArrayList. And yes, it won't be a copy, it will be a reference to the same object in memory. So whatever you do will affect both of them. You need to either manually copy over all the information you need or to use a clone() or copy() function.
So for example, in your code, the line VoipBlock vb3 =new VoipBlock(); is a bit redundant because you're overwriting the new instance straight away.
What you really need here is to either use a copy constructor or declare VoipBlock to be Clonable so you can use the clone() method.
What you are interpreting as passing by reference is not actually passing by reference. Java objects are really pointers. Because of this you are passing the value of the pointer. So when you do:
vb3=sortedBlocks.get(0);
you are really assigning vb3 to point to the same locations in memory as sortedBlocks.get(0). Therefore when you manipulate vb3 properties through their setters, the result is seen in both.
If you want two separate pointers you need to use the new keyword or use the clone() method which does this under the hood.
An example to prove this is:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public void doSomething(Person p) {
p = new Person("Bob");
System.out.println(p.getName());
}
public static void main(String[] args) {
Person p = new Person("Billy");
System.out.println(p.getName());
doSomething(p);
System.out.println(p.getName());
}
}
Since Java is pass by value the output will be: Billy, Bob, Billy. If Java were pass by reference it would be Billy, Bob, Bob. If I did not do the new Person in the doSomething() method and instead used the setName() method I would end up with Billy, Bob, Bob also but this is due to the fact I'm now modifying off the same pointer not that I passed by reference as the example above proves that's not the case.