I have a Java class that has a few members. I want to write a custom cast for it. I was wondering how is it possible to do so?
Let's assume the class is as follows:
class Person {
private int age;
private float weight;
// getters and setters and etc
}
I would like the int cast to return the member age of an object, and the float cast to return the weight of an object.
For instance:
public class Main {
public static void main(String[] args) {
// create an object
Person P = new Person();
P.setAge(21);
P.setWeight(88.0);
// case 1: casting object to an existing data type
int personAge = (int) P; // would return the age
float personWeight = (float) P; // would return the weight
// case 2: casting an existing data type to an object
Person P2 = (Person) personAge; // this would create an instance of the object whose age is assigned and weight is not assigned
}
}
I was wondering if it is possible to do the opposite. In particular, casting int to Person would return an instance of Person that its age is assigned and similarly for float.
I know this question may not have an answer. But because I did not find any useful results in my search, I decided to ask it.
P.S. I understand that for a String, the toString method would take care of case 1.
You can't overload the cast operator. Java doesn't support it and probably never will.
To convert a single value to an instance of the desired class, we use static factory methods.
public static Person fromAge(int age) {
return new Person(age);
}
They often return a partially constructed object. In the snippet above, a newly constructed person has only age set: other fields will have their default values.
To do the opposite, we use getters.
public int getAge() {
return age;
}
However, since toString is already there, it makes sense to add other data types as well.
toInt makes no sense when it's applied to me (as an instance of the Person class). It could be my height, my weight, my age, a number of times I went to a bathroom today, etc. I can't represent myself by one int number, neither can a large majority of classes.
On the other hand, toString can do this job pretty well: I can give you (read return) a summary of my hobbies, my biometric information, even my picture. Or I can leave it to the default implementation, which still would satisfactorily represent an object.
You wouldn't use a cast for this just write methods in your Person class to get those values.
public int getAge()
{
return age;
}
etc.
So I've only done this once and I'm unsure whether the approach I did is the appropriate way.
But my approach was a method called typeConverter, which i would give an object as parameter, then you could take that parameter and look what object type it is and then create a new Person, with your value.
Although this approach could cause problems, when your class would have two integer fields. But I think you could find a solution for this, by giving it another parameter that defines, which field you'd want to convert it to.
I'm really sorry for my poor english, but I hope you get the principle.
Related
This question already has answers here:
Can someone explain a void return type in Java?
(5 answers)
Closed 6 years ago.
I'm confused about "void",
as it pertains to methods.
I don't know what the distinction between two methods is when one has "void" and another doesn't.
For example, if I do:
Public meth (int amount)
{
amount = initial * interest;
return amount;
}
( not sure if it was right, or even valid, to take the name "amount" and name it the same thing as my formal parameter, but what makes sense here is that you're performing a calculation and returning the result)
Then, if I did something like:
Public void Testing (int array[])
{
//code that would modify the internals of an array
}
Would the second one have no "return" because it's more of a general method, that can be applied to any integer array, while the first one is about doing work on specific variables?
Would also appreciate one or two more examples of when I would or wouldn't be using "void" and "return".
One other thing that seems to confuse me is calling methods.
I know sometimes I'll do something like, for example, using the Testing method above,
Testing(ArrayName);
Other times, it will be like:
NameOfWhateverImApplyingMethodTo.MethodName();
And then there are times when things will be done properly by:
Thing1.MethodName(Thing2);
Which circumstances would I switch the syntax for method calls like this?
Java is case sensitive, so the modifier Public is invalid, use public
You can't define a method as public methodName(int a), only a constructor has this signature, a method must be public void methodName(<signature>) for methods that don't return anything or public <return type> methodName(<signature>) for methods that do.
Void basically means that the method will not return anything.
If you did
String name= "tim";
public void getName(){
return name;
}
This would result in an error, because the getName method is returning a string object called name, but the method declaration is saying I am returning nothing - because it is void.
Instead the method should be :
String name = "tim";
public String getName(){
return name;
}
Now when the method getName() is called it will return a string object "name" with "tim" inside of it :)
You might have void for a set method. So for example
String name = "tim";
public void setName(String newName){
this.name = newName;
}
When this method is called you would use setName("Andy"); and it would set the value of the name variable to be "Andy". Nothing is returned in this method, because it is setting something, but there is no need to send anything back, so we use void on the method declaration.
Hope this helps.
The method that has void as return type does not return anything. For example you want to set a field firstName in your class. You will write a setting method like
public void setFirstName(String n) {
this.firstName = n;
}
As you can see you are just setting a class variable and does not require to return anything.
If you dont use void then you have to provide a return type for method. Like if you wish to write a getter for above variable as:
public String getFirstName() {
return this.firstName;
}
Once you provide a return type, you will have to return a value of that type otherwise your code will not compile.
Calling a method can be done based on where you are calling it from and what modifier is used:
If you are calling the method from the same class then you can simply write firstName = getFirstName()
If you are calling the method from another class then you require object of method's class as qualifier like personObject.getFirstName()
If you are calling a static method then you require class name as qualifier like Person.getFirstName();
Return type is what you get out of it. When you call it, what are you hoping to get back? For instance, if the method gets the average of two numbers, then you're expecting a number back, so the return type will be a number type, like "int" (integer).
You can see what it should be using that logic or by looking in the method for the word return - what comes after return is what is returned, and its type should be declared in the method (e.g. if it says "return 4;" it's returning an int, and should be e.g. public int getFour()
You also asked about e.g. testing() vs testing(word)
I remember having the same difficulty. The distinction between the two also relates to the method declaration line. I'll illustrate.
public String testing(){
return "a word";
}
Calling this method by doing "System.out.println(testing());" should print "a word". Calling this method by doing "System.out.println(testing("a word"));" will give you an issue - this is because when you call testing, it looks at the appropriate method: one in the right class, with the right return type and with the right arguments/parameters. If you're calling testing("a word"), that means you're using a String as an argument (because "a word" is a string), and so it tries to use the testing(String aString) method - which doesn't exist.
So you use empty brackets when the method takes no input, and you put stuff in brackets when the method expects stuff. This should be less confusing than it sounds, because it's usually logical - if you want to call a method that returns an average, you need to ask yourself "Average of what?" You'd probably need to supply it with the values you want the average of.
Moving on: (a) testing() versus(b) AClass.testing() versus(c) aclass.testing() -
In (a), there's no class specified. Therefore, if you call it from that class, Java can guess which class: this one, and it'll work. From any other class, it won't know what you're talking about, and might even insult you.
In (b), you're specifying a class in general - therefore it'll know what class to find it in - and it'll work if it's a "static method". *[see bottom]
In (c), you're specifying an instance of AClass you want to run "testing()" on*.
For instance, imagine you've created a class called Business. You make a hundred Business objects by specifying for each a name, number, address.
e.g.
Business b = new Business(name, number, address);
Then in the Business class you have a method "getName()". This method takes no argument - you could see that the brackets are empty - so if, from another class, you call "Business.getName()", how could it know which name you want? You've just made a hundred businesses!
It simply can't. Therefore, for such a method, you'd call "b.getName()" (b being the Business we created above) and it would get the name for this instance of a Business - namely, b.
I'm happy to help, so if you're confused about any particular parts of what I just wrote please let me know and I'll try to elaborate!
edit: A bit on static methods:
Static methods don't belong to an instance of the class. getName(), for example, would get the name of this Business - ie, this instance of the Business class. But let's say that in the Business class you made a method that took the first letter of each word in a String and transformed it to uppercase - like if you wanted to make the business names look more professional when you printed them out.
public static String stringToUpperCase(String aString){
aString = aString.substring(0, 1).toUpperCase() + aString.substring(1);
return aString;
}
And to use that, you change the getName() method from:
public String getName(){
return name;
}
to
public String getName(){
return stringToUpperCase(name);
}
The new method is used here to make the name have an uppercase first letter - but that is the extent of its involvement with the Business class. You notice it doesn't ask for information about the name, address, or number for a particular business. It just takes a string you give it, does something to it, and gives it back. It doesn't matter whether you have no Businesses or a hundred.
To call this method, you'd use:
System.out.println(Business.stringToUpperCase("hello"));
This would print Hello.
If it were not a static method, you'd have to make a new Business first:
Business b = new Business("aName", "aNumber", "anAddress");
System.out.println(b.stringToUpperCase("hello"));
And if the method did need access to more Business-instance information (like a business's name number or address) it wouldn't be able to be an instance variable.
The first example, a method without a return type at all, is a constructor; used when an instance is created with new. However, you can't return a value from a constructor. Something like,
this.amount = initial * interest; // return amount;
Sets the field amount to initial * interest.
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 9 years ago.
Improve this question
I am new to Java and this was a example I found in the book I am reading.There are several things I do not understand in this code.Please help me to understand it.
/*
* CalculatorModel
* Encapsilates the data model used by the calculator Application
*/
public class CalculatorModel{
private double operand1;
private double operand2;
public void setOperand1(double value){
operand1=value;
}
public void setOperand2(double value){
operand2=value;
}
public double getOperand1(){
return operand1;
}
public double getOperand2(){
return operand2;
}
public String toString(){
String s = "operand 1=" + operand1 + "operand 2=" + operand2;
return s;
}
}
/*
* CalculatorHelper
* A class that performs mathematical functions for a calculator program
*/
public class CalculatorHelper{
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
public void setOperand1(double value){
calcModel.setOperand1(value);
}
public void setOperand2(double value){
calcModel.setOperand2(value);
}
public double add(){
return calcModel.getOperand1()+calcModel.getOperand2();
}
public double subtract(){
return calcModel.getOperand1()-calcModel.getOperand2();
}
public double multiply(){
return calcModel.getOperand1()*calcModel.getOperand2();
}
public double divide(){
return calcModel.getOperand1()/calcModel.getOperand2();
}
}
Please help me to understand what is done by
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
in the calculatorHelper class. Is calcModel a variable a variable of type CalculatorModel? What is the difference of having a object as a data type than a primitive data type to a variable?
If calcModel is a variable what is done by the line calcModel=new CalculatorModel();
I don't understand why it is important to have two classes as CalculatorModel and CalculatorHelper.
What is done with the method
public void setOperand1(double value){
calcModel.setOperand1(value);
}
in the helper class as there's already a setmethod in CalculatorModel class.
This is what I tried and what's wrong with this code?
public class Calculator{
private double num1,num2;
public void setValue1(double value1){
num1=value1;
}
public void setValue2(double value2){
num2=value2;
}
public double getValue1(){
return num1;
}
public double getValue2(){
return num2;
}
public double add(){
return getValue1()+getValue2();
}
public double subtract(){
return getValue1()-getValue2();
}
public double multiply(){
return getValue1()*getValue2();
}
public double divide(){
return getValue1()/getValue2();
}
}
"What is the difference of having a object as a data type than a primitive data type to a variable?"
Programming is all about data. Classes you can consider as complex data, and primitives as simple data. Say you have a class School
public class School {
}
What does school have? It has students. You can't represent a student with an of primitive types, because it just doesn't make sense for a student to be a double, int boolean, etc. So a student is another complex data type, like a school. So in order for the student to be represented as data contained by the school, you need a Student class also, which can hold the student's name, address and such
public class Student{
String firstName;
String lastName;
String address;
int age;
So to fully represent the student being in the school you use the has-a relationship, where School has-a Student
public class School {
Student student;
}
To delve even deeper, does a school only have one student? No, it should have many students. So you would represent that as a School having an array of Students
public class School {
Student[] students;
}
So in terms of data, you have a data tree like this now
School
Student
firstName
lastName
address
age
Student
firstName
lastName
address
age
This is the basic idea behind Object Oriented Programming. It's a lot easier to comprehend when you look at objects as actual physical objects. It makes it easier to understand the relationships.
Yes, your assumption that calcModel is a variable object of type CalculatorModel is right. when you say calcModel = new CalcModel(); it is actually creating another object in memory for storing the data that is to be stored(both operands) and storing the address of that object in calcModel. This way you can refer to object you created earlier. If you have worked with c earlier you can easily say calcModel is a pointer where as the object created is the data in the address located in the pointer.
The difference between a primitive type variable and object type variable is that the actual data that is to be stored in the variable is much more complex. For example the class CalculatorModel is a combination of two doubles... You can carry both operands as one entity by combining them(encapsulating) in a class. An object may also contain methods that can do some operations on the data stored in its member variables.
It is not necessary to have two classes, some people like it that way. I'm positively sure there is no need to create two classes in this case. Both can be merged as you have obviously did. Mind you there are no right and wrong ways to code, some ways of doing it are more preferable because they are more popular and avoids readability issues in long run. setOperand1() method is just using calcModel.setOperand1() so I don't see a necessity to have it done that way, calcModel.setOperand1 can be called directly from where ever setOperand1() is called. However, there can be case where you want to hide which function of setOperand1 is to be called or some complex operations are to be performed before calling calcModel.setOperand1. In such cases where you want to reduce burden for the callers of calcModel.setOperand1 by created setOperand1().
There is nothing wrong with the code. However you don't have to use getValue1() & getValue2() function in your add, subtract and other mathematical operations. you can simply say return num1+num2 Because, num1 & num2 are member variables of the same class.
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
in the calculatorHelper class. Is calcModel a variable a variable of
type CalculatorModel ?What is the difference of having a object as a
data type than a primitive data type to a variable? If calcModel is a
variable what is done by the line calcModel=new CalculatorModel();
The variable calcModel is an instance of CalculatorModel, but is a class variable to the class CalculatorHelper. If you want to know about primitive data type vs object data type, check this article out. This line calcModel=new CalculatorModel(); is initializing the variable. You must do this in order to actually use the methods. Read more here.
I don't understand why it is important to have two classes as
CalculatorModel and CalculatorHelper.
There are cases where helper classes/methods are useful when it comes to separating large chunks of logic. Check this article out.
public void setOperand1(double value){
calcModel.setOperand1(value);
}
in the helper class as there's already a setmethod in CalculatorModel
class.
Yes, and it's calling that same exact set method but from the CalculatorHelper class.
This is what I tried and what's wrong with this code?
There seems to be nothing wrong with the code. I'm assuming you're using it properly from the main method (or whatever method you're using the class in).
This is essentially a Delegate Pattern by which the author has implemented the Calculator.
The Calculator serves the abstraction of the real-life Calculator.
By providing the helper/delegate class , I separate the behavior of the object.I am free to write my own implementation of add / subtract using a helper class. Calculator will serve as the Model of your calculations.
Consider this , If you try to modify the behavior you need to change the whole Calculator class and distribute it to the Client. However , I don't have to modify the Calculator but only the Helper which the client does/might not ship.
There is nothing wrong in what you have done - but consider this - what if you want to have Single instance of the Calculator - you can control instantion using helper class (in this case)
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
is composition which is used here to separate concerns. The CalculatorHelper's concern is to know how to do addition, substraction, .. while the CalculatorModel knows the values, how to provide them to the outside and how to store them.
CalculatorHelperhas therefore an instance ofCalculatorModel` to which it can delegate all the things it does not know about. E.g.
public void setOperand1(double value){
calcModel.setOperand1(value);
}
The overall design is still questionable. First of all is it a bad encapsulation of a "calculator" because none of math operation reflect back to the model in any way. There needs to be a third class (CalculatorHelperHelper?) that knows how to deal with more than two operands.
It is also questionable whether or not a CalculatorModel should have two values at once. Two separate value objects would IMO make a lot more sense and would result in more modular code that would also be easier to understand as composition of objects.
The last point in this example is that encapsulating "storage" of values into CalculatorModel does not provide any real benefit here. It would if there was some kind of database backend or otherwise "complicated" logic that does not belong into CalculatorHelper. I would have taken more or less your approach in a simple real world scenario. Your code is not wrong. It's just a different approach.
The code in the context of the book and given that it is an example to show some design techniques is ok for that purpose. I would just do it very much different if I was to write a calculator. OO design is on the other hand not right or wrong and people can argue a lot about what good design is.
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 9 years ago.
Improve this question
This question may seem dumb at first, but after having worked with different person, I see everyone seems to have their own, different knowledge about it, so here's my question.
So now I'm wondering what is the best way to do it, and why ("why" is more important for me):
I'm wondering about two methods to write Java code:
Do you always pass Object or can you pass primitive data type ?
Do you call variables using this.name, name or getName() inside your class instance ?
public class MyClass {
private String someStr;
private int someNumber;
private Integer someOtherNumber; // int, Integer ? which one to choose ?
public MyClass(String someStr, int someNumber, int someOtherNumber) { // int someNumber ? Integer someNumber ? why ?
this.someStr = someStr; // Here, it's clearly this.{name} = {name} because of the variable name conflict
this.someNumber = someNumber;
this.someOtherNumber = someOtherNumber;
}
public int someMethod(boolean first) { // Boolean ? boolean ?
if (first) {
return someNumber;
} else {
return this.someOtherNumber; // this.{name} ? just {name} or even this.get{name}() or get{name}() ? (supposing getters exists)
}
}
}
I hope someone will provide me with a great explanation about which to use in order for me to write better code.
Do you always pass Object or can you pass primitive data type ?
You can't pass an Object, only a reference to an Object. You can pass primitive data.
Do you call variables using this.name, name or getName() inside your class instance ?
I don't make it more complicated than I need to, unless it's conflicts with a local variable or my getName() does something special, but that is a matter of style.
Do you always pass Object or can you pass primitive data type ?
You can pass primitives or references to objects depending on your need.
Do you call variables using this.name, name or getName() inside your
class instance ?
this is used to refer to the current object. If there are conflicting variable names and you want to distinguish between the object variable and local variable then use this.
Also you seems to be confused about primitives and Wrapper classes. Wrapper classes provides utilities methods and are of use especially working with collections.
If you need to work with the primitive data types then you should use them, e.g., int, double, char, float, etc. The only exception is String which in Java is a special class that represents a char array and also holds instance methods.
The case with Integer vs int, is when you need to use Integer methods (http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html). But if you only need a data type to hold your value then choose int.
Do you always pass Object or can you pass primitive data type ?
public int someMethod(boolean first) { // Boolean ? boolean ?
}
In the following example, you can pass boolean and Boolean with the same success. In Java this is called Autoboxing.
N.B. Be careful, because when passing an object it may be null!
Do you call variables using this.name, name or getName() inside your
class instance ?
Depends. If name is an class member variable, you can access it with name if there isn't any other variable in the current scope that has the same name. In this case you should use this.name to point exactly to the class member variable. getName() may be used, as well. It's just a matter of style.
I keep it simple. I'm using name, but if I have a local variable with the same name I must use this.name (my prefered solution) over getName().
getName() must be used if it do some logic like validation.
Do you always pass Object or can you pass primitive data type ?
It depends on your application and your needs. If you pass a reference to an object, you are able to use the methods of the related type which may be more secure and portable. Let say you are using the class Double. Double has many peer-reviewed and tested methods which may be helpful to you.If you prefer to use primitive type, double, you need to be careful in your manipulations like comparing, validating etc.
For performance issue, you may check a previous discussion below:
Why do people still use primitive types in Java?
Do you call variables using this.name, name or getName() inside your class instance ?
I prefer using this when I refer a class member because i think it will be helpful for others reading my code to understand that the variable is a class member.
Finally, whatever style you prefer, I think you should stick to it in your applications.
Do you call variables using this.name, name or getName() inside your class instance ?
It is mostly a matter of personal style and principle.
private int someOtherNumber; I almost always use int because it seems more natural to me --perhaps influenced by the C days. And, from performance and memory usage point of view using int is a better choice. As a rule of thumb, I don't use objects for primitives unless I have a good reason to.
return this.getSomeOtherNumber(); I prefer using getters/setters; since sometimes -not always- the getter method is not just a simple return statement, rather it encapsulates some logic. As a result, I don't directly access class attributes (like this.someAttr or someClass.somePublicAttr) unless it's a final attribute. Believe me, it's much safer.
Continuing 2: It may seem a bit strange but I, having a strong Lisp background, try to avoid using even getter/setter methods (class state) as much as possible and instead explicity pass the required parameters and use the methods' return values. Consider the following example:
public class C {
private int a;
private int b;
public int getA() { return a; }
public void setA(int a) { this.a = a; }
public int getB() { return a; }
public void setB(int b) { this.b = b; }
// Usual style
public void someMethod1(int x) {
mainLogic1(x);
}
private void mainLogic1(int x) {
b = a + x;
}
// My preferred style
public void someMethod2(int x) {
setB(mainLogic2(x, getA()));
}
private int mainLogic2(int x, int a) {
return x + a;
}
}
As you can see, someMethod1 and mainLogic1 both have side effects which are hard to detect when looking at the code. On the other hand mainLogic2 doesn't have a side effect at all and someMethod2 side effect is easier to spot by just looking. This may seem like overkill, but it has made my Java code more readable, more testable and easier to refactor as it consists of large number of small methods with no side effects.
This question already has answers here:
How to avoid constructor code redundancy in Java?
(4 answers)
Closed 9 years ago.
Hi I am just learning about constructor chaining in Java and had some questions...
First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.
In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?
import java.util.*;
class Employee
{
private String name;
private double salary;
public Employee()
{
this("James Bond", 34000);
}
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public static void main(String[] args)
{
Employee a = new Employee();
}
}
Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.
static int numOfExamples = 0;
public Example(String name, int num)
{
this.name = name;
this.num = num;
numOfExamples++;
System.out.println("Constructor called.");
Log.info("Constructor called");
}
public Example()
{
this("James Bond",3);
}
That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.
Chaining constructors like this is useful to avoid repeating code, and helps with maintainability:
public MyClass(int x, double y, String z) {
// set fields
}
public MyClass() { // i.e. a constructor that uses default values
this(42, 4.2, "hello world"); // x is 42, y is 4.2, and z is "hello world"
}
If we didn't use the chain, and wanted to change how the x argument (for example) is processed when constructing an instance of MyClass, we would have to change code in both constructors. With the chain, we only need to change one of them.
1) As others have said, it's for code maintenance, basically the idea is that you only write one piece of code once, which means you only need to edit it once, there is no risk of overlooking something when editing your methods and the two accidentally becoming different.
Personally I tend to use this differently than in your example. Like so:
Employee() {
setupStuff();
}
Employee(String name) {
this();
this.setName(name);
}
This is a nice way of doing things, because potentially your setter can be way more complicated than just setting a member in the class. So basically what this does is puts calling the empty constructor and then a setter into a single method, making it much easier for anyone using the class.
2) The constructor being called doesnt't create a different object at all, it creates this object. Note that there is no new keyword used. Basically you're just calling a different method inside your constructor, except that method happens to also be a constructor.
Every time you want to allow constructing an object wit default values, and also want to allow creating the same object with non-default values. Let's imagine a DateTime class. You could want to initialize it with the current time by default, or with a specific time. Imagine a Car class. You could imagine constructing it with Black as the default color, or with a specific color. This kind of situation is very common. See java.util.ArrayList or java.util.Locale, for concrete examples.
It's stored in the name field. So you access it, from the object itself, with this.name (this being optional, just as in the getName() method).
How do I access this new "James Bond" object for future use?
Because you saved the values of name and salary as fields of your employee class, then inside the employee class you can use those fields, and outside your employee class you can use the getter/setter methos of your employee class
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.