Implementing 2 linked lists in java without pointers - java

I am facing problems while trying to implement 2 linked lists in my Java code.
If I declare my "head" variables in main and pass them to any function, they could not be modified by that function as the referencing variable would be local to that function.
But if I make them class variables, the called function could not know which of the 2 "head" variables I am referring to.
This problem could be easily solved in C language by passing double pointers in functions so that the local variable can modify the passed variable but how to solve this problem in Java? Thanks.

Pointers aren’t used in Java
Defines the attribute at the class level and don't use it in the signature of your methods, or return the value of your function to the original variable.
public class MyClass{
private string value;
public myFunction(){
value = toto; // this will change the value of the attribute directly
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.myFunction(); // The new value is saved at the class level
}
}
or
public class MyClass{
public String myFunction(String value){
value = "toto";
return value; // The value modified is return back to the caller
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
String myValue = myClass.myFunction(myvalue); // The new value is saved
}
}

Related

How can I refer the objcet that calls a method in the method in Java? [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word

Changing the value being passed through the parameter

I was testing whether you can change the value of the static variable x by passing it through a parameter, but I found out that you can't do it like that.
public class Test {
static int x;
static void changeX(int x_) {
x_ = 50;
}
public static void main(String args[]) {
changeX(x);
System.out.println(x);//it prints out zero because the static variable did not get changed
}
}
If we do it like this, we can change it:
public class Test {
static int x;
static void changeX(int x_) {
x = 50;
}
public static void main(String args[]) {
changeX(x);
System.out.println(x);
}
}
Which means you have to directly reference to the static variable in order to change it. Okay. Now. My question is, is there a way to change a class variable by just passing it through the parameter, without referencing it in the implementation? Basically, is there a way to use the first way somehow? Thanks.
You can achieve what you are asking, but you need to be aware of the subtle limitations. You can modify an object reference passed into a method, but you cannot reassign the reference in the method and have the original object be changed.
Java is always pass by value. Period.
Object references, are passed by value, but it is through those references (which point to the same memory location), that you can modify objects inside of methods, through the parameter.
You cannot modify primitives (int, float, boolean, etc) in this manner, they are always passed by value. You also cannot modify immutable objects (such as String), as they cannot be changed using a public interface.
Consider this simple example, which tests creating an object with some modifiable fields, by-value, and by-reference (it's modifying by object reference, that itself is passed by value):
public class ParameterPassingTest {
static SomeObject someStaticObject;
public static void main(String[] args) {
// initialize a static object reference
someStaticObject = new SomeObject("I am a static Object", 10);
System.out.println("My static object before: " + someStaticObject);
// try modifying the reference by value
modifySomeObjectByValue(someStaticObject);
// try printing the value, it will be the same
System.out.println("My static object after mod-by-value: " + someStaticObject);
// now, try modifying by object reference
modifySomeObjectByReference(someStaticObject);
// print again. new values should be observed
System.out.println("My static object after mod-by-reference: " + someStaticObject);
}
// this method tries to modify the original object by assigning directly to the method parameter. It won't work.
public static void modifySomeObjectByValue(SomeObject someObject) {
SomeObject newObject = new SomeObject("I am another object, from a local method", 20);
someObject = newObject; // try to modify the original object by assigning to the parameter directly
}
// this method tries to modify the original object by using the object's public interface. It works.
public static void modifySomeObjectByReference(SomeObject someObject) {
// try to modify the original object by using the reference passed in
someObject.setaString("I have been modified by a method");
someObject.setAnInt(50);
}
}
// simple, generic class object with some fields.
class SomeObject {
String aString;
int anInt;
public SomeObject(String aString, int anInt) {
this.aString = aString;
this.anInt = anInt;
}
public String getaString() {
return aString;
}
public void setaString(String aString) {
this.aString = aString;
}
public int getAnInt() {
return anInt;
}
public void setAnInt(int anInt) {
this.anInt = anInt;
}
#Override
public String toString() {
return "aString = " + getaString() + " | anInt = " + getAnInt();
}
}
This produces output:
My static object before: aString = I am a static Object | anInt = 10
My static object after mod-by-value: aString = I am a static Object | anInt = 10
My static object after mod-by-reference: aString = I have been modified by a method | anInt = 50
Java passes primitives always as value. Objects on the other hand are always passed as reference. In your second example, you access the static attribute x and not the parameter x_.
Furthermore, static does not protect an attribute from being rewritten. It binds an attribute to the class (without static attributes are bound to objects). Maybe you meant final?
EDIT: corrected a typo.

Java - call a variable from another class [closed]

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 8 years ago.
Improve this question
Within my main method I'm trying to understand how to call up a variable from a different class.
I've attempted to break it down to the most simple solution possible just so I can get my head around the logic involved.
I have two classes within my package "var":
Class 1 - Source.java
package var;
public class Source {
int source1;
class setSource{
int source1 = 5;
}
}
Class 2 - Var.java
package var;
public class Var {
public static void main(String[] args) {
int Var;
Var = Source.setSource();
}
}
First time post here but I've spent 4 days and almost all my spare time trying to figure this out, please be gentle I'm dedicated but extremely newbie right now. Thanks in advance, I hope I've submitted this correctly.
Okay, I can sort of see what you were thinking but you've got some of the semantics incorrect. What you want to define is a method. A method takes the following structure:
<access modifier> <return type> <method name> (<method arguments>)
So for example
public void doSomething(String value) {
// This is the public method that returns nothing. It is called doSomething
// It expects a string value that it will call "value"
}
In your case, you want to create one of these, and you want to make a setter and a getter (or accessor and mutator if you're being posh).
Your Setter
This is just a normal method. Its purpose is to set the value of some class field. So let's define our class..
public class MyClass {
private int num;
}
Now we've got a class MyClass with a field num. But oh no, it's private, so let's create a setter so that the user can update the value.. Following our formula for methods, we start with a public access modifier. We then define the return type, which is void because it returns nothing. The name of the method should follow the java naming convention, which is the word "set" followed by the name of the member and finally the value for the setter.. Or all together:
public void setNum(int num) {
this.num = num;
}
This will update the value in the class with the value that you pass in. Excellent!
Your Getter
Well, this is nice and simple. Following our formula, it is a method that is public because everyone can access it; it returns something (in this case int) so that is the return type; the name follows the convention of "get" followed by the name and it expects no parameters.
public int getNum() {
return num;
}
This will return the value of num.
Finally, Using them!
public class MainClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
// Create a new MyClass instance.
myClass.setNum(4);
// Update the value in the class with the number 4.
System.out.println("The number is " + myClass.getNum());
// Outputs: "The number is 4"
}
}
you are using static calls, so you have to set this variables public static :
public static int source1;
and access them directly:
Var = Source.source1;
Your concepts are not well polished.
Your classes should have been like this
public class Source {
private int source;
public void setSource(int src){ // Called setter
source = src;
}
public int getSource(){ // Called getter
return source;
}
}
And
public class Var {
public static void main(String[] args) {
int Var;
Source source = new Source();
source.setSource(10);
Var = source.getSource(); // Var has value 10 in it.
}
}
Source is a class, you'll need to create an object that's a member of this class and then call the method on it. Additionally, the syntax for your method call is incorrect.
package var;
public class Source {
int source1 = 1;
public void setSource(){
source1 = 5;
}
}
Then:
package var;
public class Var {
public static void main(String[] args) {
Source source = new Source();
System.out.println(source.source1);
source.setSource();
System.out.println(source.source1);
}
}
I hope that makes sense to you when you compile it and run.
(Note that Java is case sensitive. On the above example, Source is the class and source is the object).
An alternative would be to declare methods and fields as static (static methods are called directly on the class), but I would suggest you make sure you understand the basic concepts of class and object instantiation before moving on to that.

How to access the same object from multiple classes in Java

I've been looking for the answer to this problem all day.
I have a value class that holds a variety of values as long as the program is running.
I create a new Value object in class A, and store an int value.
Class A also has a printMoney() method.
public class A {
Value value = new Value();
value.setMoney(100);
public void printMoney {
System.out.println(value.getMoney);
}
In class B, I want to be able to call printMoney() from class A, so logically I do the following:
public class B {
A a = new A();
a.printMoney();
}
This does, however, return '0' as a value instead of '100'.
I understand that by creating an A object, I automatically create a new value object, which has its default money value. So, basically my question is; how do I solve this?
Make the object static. static Value value = new Value();
static variables are shared across all the objects
So the change made in static variable will be reflected for all the objects of class.
if you want to get that value in A you have to assign the value in A construtor, like
public class A {
Value value = new Value();
public A() {
this.value.setMoney(100);
}
otherwise, you can make the value static
you should receive the instance that creates the object B and save it then you would be able to call it
like so:
public class A {
B b = new B(this);
}
public class B {
A a;
public B(A a) {
this.a = a;
}
private someMethod () {
a.printMoney();
}
}

java linked list problem

I have written some Java code with 3 simple classes where the first, Controller, has the main method and creates the instances of the other classes. Floaters is a classes that creates a linked list of Floater instances, each with a particular length and boolean value to say if they are vertical or not. My problem, as it says in the commented lines of the first class, is that both "humans" and "otters" Floaters instances are getting assigned the same values and thus have the same size....
Any suggestions on how to fix this?
Thanks in advance!
public class Controller{
private static Floaters humans;
private static Floaters otters;
public static void main(String[] args)
{
otters = new Floaters();
humans = new Floaters();
otters.addFloater(2, true);
otters.addFloater(3, true);
//this should read "2" and it does
System.out.println(otters.size());
//this should read "0" but reads "2". Why?
//How can I get it to read "0"?
System.out.println(humans.size());
}
}
import java.util.LinkedList;
public class Floaters {
private static LinkedList<Floater> llf;
Floaters()
{
llf = new LinkedList<Floater>();
}
public void addFloater(int length, boolean is_vertical)
{
Floater floater = new Floater(is_vertical, (byte)length);
llf.add(floater);
}
public int size()
{
return llf.size();
}
}
public class Floater {
int length;
boolean is_vertical;
Floater(boolean is_vertical, int length)
{
this.length = length;
this.is_vertical = is_vertical;
}
}
The llf in your Floaters-class is static. When you make variables static, they're linked to the class rather than the instance, and thus both instances of Floaters use the same list.
To correct this, simply remove the static from your declaration of the variable.
in floaters, llf should NOT be static
Because of static:
private static LinkedList<Floater> llf;
In this case static means a class field, shared among all instances of a class.
For example - mathematic functions in Java are declared as static metohods of the class java.lang.Math, matemathematical constants are static atributes of this class. So if you use sin(x), you are using always the same method.

Categories