Java Pass-by-reference not working?

Question:

I'm trying to make this little game in Java but I seem to have stumbled upon a variable reference problem. My Entity class, which Player extends from, keeps a variable of type Dimension. This Dimension gets set via the constructor of the Entity class like so:

Now, whenever I call this resetOverWorld method from anywhere, it seems like my activedimension really did refresh, but the dimension stored in my Player/Enitity class didn't. I'm fairly new to Java, so I don't know if I'm doing something wrong with the variable-references being passed through constructors and methods. My application seems to copy a dimension object somewhere instead of passing the reference, but I can't figure out where.

Any help or thoughts are welcome. Thanks in advance ~Krikke

Answer:

The problem is that you aren't updating the reference in your Player class. When you store your Dimension in your Entity constructor you are storing a reference to that Dimension in memory. In your resetOverWorld() method you change the overworld and activedimension variables to point to a new OverWorldDimension but all the references elsewhere (e.g. your Entity objects) haven't changed. They still refer to the initial Dimension they were constructed with.

You might want to consider having a DimensionTracker class that your Entity could hold instead, allowing you to change it's internal Dimension from a single location. Otherwise you need to update every Entity to refer to the new Dimension.

Related:

java,while-loop,java.util.scanner
I've looked at similar questions and tried to follow the answers that solved the issues that others have had but putting the sc.next() or sc.nextLine() after the while loop causes it to go into an infinite loop. The problem is if a user enters incorrect input (nothing or a number)...

java,regex
I have a string where I have the user should be able to specify xpaths that will be evaluated at runtime. I was thinking about having a the following way to specify it. String = "Hi my name is (/message/user) how can i help you with (/message/message) "; How can...

java,android,string
I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

java,jdbc
I am trying to get the stop_name of the last inserted row in the table with preparedStatement. How can I get the last inserted one? I appreciate any help. behavoiur table: CREATE TABLE IF NOT EXISTS behaviour( behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, mac VARCHAR(30) NOT NULL, stop_name VARCHAR(30)...

java
I am have a project that need to modify some text in the text file. Like BB,BO,BR,BZ,CL,VE-BR I need make it become BB,BO,BZ,CL,VE. and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR. I have tried to type some code, however the code fail to loop and also,in this...

java,spring,rest,maven
I am working on a basic Hello World program using Spring and Restful webservices. But when I try to call my service I am getting below error message: HTTP Status 406 - description - The resource identified by this request is only capable of generating responses with characteristics not acceptable...

java,spring,logging,lightadmin
I have a Java web application which use Spring and Hibernate and I plan to use lightadmin to provide an administration interface. However, I found very little information about the logging part of lightadmin : if I have such an adminsitration interface, I would like that any operation made to...

java,android
is there any way to get the distinct values of a custom arraylist? public class mystatistic extends BaseActivity { public String objectid; public String playerid; public String playername; public String enemyid; public String enemyname; public String question; public mystatistik(String objectid, String playerid, String playername, String enemyid, String enemyname, String question)...

java,android,gps,geolocation,location
Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

java,literals,octal
This question already has an answer here: How does a leading zero change a numeric literal in Java? 3 answers Here is some code in java on datatypes: class Test { public static void main(String args[]) { int i = -0777; System.out.println(i); } } The output of the above...

java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

java,logging,stdout
In Java, how to block code from writing to system out? My app calls a 3rd party library that spams logs by issuing numerous System.out.println() calls. I don't have legal rights to decompile and patch the library. I'm running Websphere 8.5.x Considered using System.setOut(PrintStream out), but that will effect the...

java,android,eclipse,adt
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat http://i.stack.imgur.com/VZhuL.png package...

java,android,list,indexof
I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

java,performance,object
I have this loop which runs about 1,000,000 times. while ((line = br.readLine()) != null) { if(!(line.isEmpty())){ data = new JSONObject(line); name = (String)data.get("name"); surname = (String)data.get("surname"); ar.put(name, surname); //an array } } What are the advantages (if any) in terms of efficiency of having it like that were data,name...

java,spring,hibernate
as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

variables,maya,mel
Is it obligatory in MEL to initialize variables and especially strings when you declare them? I know that it is not necessary to initialize string arrays: string $buffer[]; $buffer[0] = "abc"; But what about strings and other variable types? Is it acceptably: string $str; $str = "abc"; Or should always...

java,android,eclipse,sdk,versions
I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

java,libgdx
I am currently using pixels as units for placing objects within my world, however this can get tedious because I only ever place objects every 16 pixels. For example, I would like to be able to place an object at position 2 and have the object rendered at the pixel...

sql,sql-server,tsql,variables,like
I'm currently working on a report that shows me all post codes covered by our sales team. Each team covers over 100 post codes. What i would like to do is create a report that brings back the clients within the post code. Currently my code looks like this. SELECT...

java,apache-spark,apache-spark-sql
I am trying to use Apache Spark for comparing two different files based on some common field, and get the values from both files and write it as output file. I am using Spark SQL for joining both files (after storing the RDD as table). Is this the correct approach?...

java,rounding
Suppose I want to round numbers that have mantissa greater than 0.3 'up' and those below 'down'. How can I do it in Java? The only thing that came to my mind was Math.round(), but I can't seem to make it follow a certain rule....

java,asynchronous,akka,blocking,future
I have a scenario where an important actor needs to make a call to a slow (15 - 20 seconds) remote system: // Non-actor code equivalent public Result makeSlowNetworkCall(Request request) { Result result = slowServiceClient.soooooSlow(request); // Could be up to 15 - 20 SECONDS (mehhhh) return result; } The Akka...

java,class,hex
I understand the structure of a java .class file, but when I want to interpret the raw hex data I get a bit lost. This is a hex dump of a class file, excluding the header and constant pool. I understand the header to be the magic number, minor_version and...

java,types,javadoc
When Javadoc'ing, I don't know whether you should explicitly say whether the parameters are of type String or int. For example /** * This method does something * @param foo an object of type Foo * @param abc the number of doors, of type int * @return the number of...

java,android,web-services
I'm trying to rewrite the application in this, in Android Studio link, which is written in Eclipse. There are two problems, first problem is there is this line in the project : import com.example.webserviceactivity.R; I couldn't write this one on Android Studio. The second problem is, in this part of...

java,android,android-intent,uri,avd
In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(R.id.button); button.setOnClickListener ( new Button.OnClickListener()...

java,elasticsearch,elasticsearch-plugin
As I know we can parse document in elastic search, And when we search for a keyword, It will return the document using this code of java API:- org.elasticsearch.action.search.SearchResponse searchHits = node.client() .prepareSearch() .setIndices("indices") .setQuery(qb) .setFrom(0).setSize(1000) .addHighlightedField("file.filename") .addHighlightedField("content") .addHighlightedField("meta.title") .setHighlighterPreTags("<span class='badge badge-info'>") .setHighlighterPostTags("</span>") .addFields("*", "_source")...

java,network-programming
I know in java we can do NetworkInterface.getNetworkInterfaces() to get all available network interfaces on local machine. Can we do similar thing where I can pass host name to get the NICs(with IPs) which are up and running?

java
input:- 1 3 4 7 9 6 -1 output:- 4 6 What I am doing is print the even numbers from the list, one per line. The list ends when -1 is encountered. Below is the my code: Scanner sc=new Scanner(System.in); for (int i = 0; i <100000000; i++) {...

java,string,printf
I'm learning Java by myself and through tutorials online. Just wondering in a printf statement, what does the different %s, %d, %15, %7, %12.2(and so on...) mean? Couldn't find any explanation anywhere online, so I'm turning to you. ...

java,selenium,browser
I'm trying to test that when I close my window a popup shows with a warning message. I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show. I could test it by using the awt...

java,jpa,glassfish,ejb-3.0
I need to delete a list of employees ignoring any integrity constraints (i.e. successfully delete the entity that doesn't related to any others yet or skip the entity that related to others) using JPA 2.0 and EJB3.0 on glassfish3.0: I iterated on the list and call entity manager in a...

java,eclipse
I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

java,vaadin
Good day everyone! How do I get the number of items that a column contains? I want to hide the "Workgroup" column if it's empty, I just don't know how. Table tblTeachings = new Table(); tblTeachings.addContainerProperty("#", Integer.class,0); tblTeachings.addContainerProperty("Course",String.class,""); tblTeachings.addContainerProperty("Teaching name",String.class,""); tblTeachings.addContainerProperty("Start date",String.class,""); tblTeachings.addContainerProperty("End Date",String.class,""); tblTeachings.addContainerProperty("Activity...

java,android,android-fragments,spannablestring
I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

java,android,listview,android-fragments,expandablelistview
In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....

java,caching,download
Okay, I've been trying to figure this out for a few hours and it's starting to kill me. I wrote a primitive version checker for an app I work on every once and awhile. It's just a simple for fun project. The version checker has been a pain though. It...

java,selenium,webdriver,junit4
I write a script on Java for Selenium WebDriver, and I have a problem with selected from dropdown menu. Here's my locator: new Select(driver.findElement(By.id("FormElement_select_68_input_input"))).selectByVisibleText("Image"); Here's an error: http://prntscr.com/7jul03 Here's HTML code: http://prntscr.com/7jvou6 Need to select "Image" from this menu, but have an error. Before I had the error like this,...