473,804 Members | 3,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does this ArrayList act like a pointer?I thought all variables in java are refere

blazedaces
284 Contributor
Before we begin let me say that I already found the solution to the problem, but I am still unable to explain why it solved the problem, so I am here to ask you experts why this java code produces the results I indeed see.

The two pairs of code I am going to show are meant to find all the prime factors of a number (it is not my original code, I took it from Project Euler, and I'm further using it solve a later, harder problem in the project, but that is not relevant).

I am going to post the first code and its corresponding incorrect result, then show the second code, its correct result, and I will lastly point out the only line that is different between the two.

The question I have for you guys, because I can't answer it, is why is the first result coming up this way? Why does the solution of changing that single line of code work?

The only explanation I can give is that for some reason if you initiate an ArrayList by saying ArrayList something = oldArrayList they are both pointing to the same ArrayList... I'm not satisfied with this answer because it doesn't make sense with the java structure I thought I knew.

So here we go:
First Code:
Expand|Select|Wrap|Line Numbers
  1.     public static void main(String[] args) {
  2.         utils.print(allPrimeFactorsAndTheirPowers(10));
  3.     }
  4.  
  5.     public static HashMap<Integer, Integer> allPrimeFactorsAndTheirPowers(int input) {
  6.         ArrayList<Integer> primeFactors = new ArrayList<Integer>((int)Math.sqrt((double)input));
  7.         ArrayList<Integer> powers = primeFactors;
  8.         HashMap<Integer, Integer> factorsAndPowers = new HashMap<Integer,Integer>((int)Math.sqrt((double)input));
  9.         int currentPower = 0;
  10.  
  11.         if (!isPrime(input)) {        
  12.             int n = input;
  13.  
  14.             if(n % 2 == 0) {
  15.                 currentPower++;
  16.                 primeFactors.add(Integer.valueOf(2));
  17.                 n = n / 2;
  18.                 while(n % 2 == 0) {
  19.                     currentPower++;
  20.                     n = n / 2;
  21.                 }
  22.                 powers.add(Integer.valueOf(currentPower));
  23.                 currentPower=0;
  24.             }
  25.             int factor = 3;
  26.             int maxFactor = (int)Math.sqrt((double) n);
  27.             while(n > 1 && factor <= maxFactor) {
  28.                 if (n % factor == 0) {
  29.                     currentPower++;
  30.                     n = n / factor;
  31.                     primeFactors.add(factor);
  32.                     while(n % factor == 0) {
  33.                         currentPower++;
  34.                         n = n / factor;
  35.                     }
  36.                     maxFactor = (int)Math.sqrt((double)n);
  37.                     powers.add(Integer.valueOf(currentPower));
  38.                     currentPower=0;
  39.                 }
  40.                 factor = factor+2;
  41.             } if (n != 1) {
  42.                 primeFactors.add(Integer.valueOf(n));
  43.                 powers.add(Integer.valueOf(1));
  44.             }
  45.         } else {
  46.             primeFactors.add(Integer.valueOf(input));
  47.             powers.add(Integer.valueOf(1));
  48.         }
  49.  
  50.         for(int i = 0; i < primeFactors.size(); i++) {
  51.             factorsAndPowers.put(primeFactors.get(i), powers.get(i));
  52.         }
  53.  
  54.         return factorsAndPowers;
  55.     }
  56.  
Incorrect Result:
5 : 5
1 : 1
2 : 2


Second Code:
Expand|Select|Wrap|Line Numbers
  1.     public static void main(String[] args) {
  2.         utils.print(allPrimeFactorsAndTheirPowers(10));
  3.     }
  4.  
  5.     public static HashMap<Integer, Integer> allPrimeFactorsAndTheirPowers(int input) {
  6.         ArrayList<Integer> primeFactors = new ArrayList<Integer>((int)Math.sqrt((double)input));
  7.         ArrayList<Integer> powers = new ArrayList<Integer>((int)Math.sqrt((double)input));
  8.         HashMap<Integer, Integer> factorsAndPowers = new HashMap<Integer,Integer>((int)Math.sqrt((double)input));
  9.         int currentPower = 0;
  10.  
  11.         if (!isPrime(input)) {        
  12.             int n = input;
  13.  
  14.             if(n % 2 == 0) {
  15.                 currentPower++;
  16.                 primeFactors.add(Integer.valueOf(2));
  17.                 n = n / 2;
  18.                 while(n % 2 == 0) {
  19.                     currentPower++;
  20.                     n = n / 2;
  21.                 }
  22.                 powers.add(Integer.valueOf(currentPower));
  23.                 currentPower=0;
  24.             }
  25.             int factor = 3;
  26.             int maxFactor = (int)Math.sqrt((double) n);
  27.             while(n > 1 && factor <= maxFactor) {
  28.                 if (n % factor == 0) {
  29.                     currentPower++;
  30.                     n = n / factor;
  31.                     primeFactors.add(factor);
  32.                     while(n % factor == 0) {
  33.                         currentPower++;
  34.                         n = n / factor;
  35.                     }
  36.                     maxFactor = (int)Math.sqrt((double)n);
  37.                     powers.add(Integer.valueOf(currentPower));
  38.                     currentPower=0;
  39.                 }
  40.                 factor = factor+2;
  41.             } if (n != 1) {
  42.                 primeFactors.add(Integer.valueOf(n));
  43.                 powers.add(Integer.valueOf(1));
  44.             }
  45.         } else {
  46.             primeFactors.add(Integer.valueOf(input));
  47.             powers.add(Integer.valueOf(1));
  48.         }
  49.  
  50.         for(int i = 0; i < primeFactors.size(); i++) {
  51.             factorsAndPowers.put(primeFactors.get(i), powers.get(i));
  52.         }
  53.  
  54.         return factorsAndPowers;
  55.     }
  56.  
Correct Result:
5 : 1
2 : 1

The only line that changes:
Incorrect Line of Code:
Expand|Select|Wrap|Line Numbers
  1. ArrayList<Integer> powers = primeFactors;
Correct Line of Code:
Expand|Select|Wrap|Line Numbers
  1. ArrayList<Integer> powers = new ArrayList<Integer>((int)Math.sqrt((double)input));
Your help and knowledge is much appreciated,
-blazed
Feb 20 '11 #1
1 7526
blazedaces
284 Contributor
I believe I found the answer:

"Array variables are references to a block of elements

When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied. For example,

int[] a = new int[] {100, 99, 98}; // "a" references the array object.
int[] b; // "b" doesn't reference anything.

b = a; // Now "b" refers to the SAME array as "a"
b[1] = 0; // Also changes a[1] because a and b refer to the same array." - http://www.leepoint.net/notes-java/d...ys/arrays.html

I had no idea this was the case, but it explains another problem I was having with arrays this time, and it completely explains what happened above.

-blazed
Feb 23 '11 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

6
8098
by: lkrubner | last post by:
I'm offering users the ability to type weblog posts into a form and post them. They type the text into a TEXTAREA which is on a form. The form, when submitted, hits a PHP script. Before it is submitted, while they are typing, I'm trying to offer them some common word processing functions. I want to implement unlimited undo and redo for the textarea. I've set the textarea to onChange="addToArrayOfPastWork()"; My undo button gives me...
3
1791
by: nicver | last post by:
I am fixing a client's Web site and for some reason an ASP class does not want to use the variables it retrieves when it initialiases. This is an excerpt of the class and it is enough to show what is not working correctly: ------ Class clsAd private pintMyData1 private pintMyData2 private pintMyData3
4
4535
by: Rich | last post by:
Dim bNcd, bNcm, bNqa, bNcur, bN0, bN1, bN2, bN3, bN4 As Boolean Dim arrBool As Boolean() = {bNcd, bNcm, bNqa, bNcur, bN0, bN1, bN2, bN3, bN4} Dim i As Integer bNcd = True bNcm = True bNqa = True bNcur = True bN0 = True bN1 = True
5
4421
by: Niu Xiao | last post by:
I saw a lot of codes like: void foo(void* arg) void bar(void** arg) f((void*)p) but what does void pointer mean in c? I just know it stands for generic pointer. thanks.
14
2433
by: jagguy | last post by:
this works char *p ; p="xat"; cout << p <<endl;
1
1383
by: archana | last post by:
Hi all, I want to develop one application for storing tasklist. so what i am doing is i have one class which is containing arraylist where i am storing details about task. At a time of serializing this it is working properly. But i am not able to deserialize back this data.
0
2880
by: dashprasannajit | last post by:
package djvusearching; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.lucene.analysis.cjk.CJKAnalyzer; //import org.apache.lucene.analysis.standard.StandardAnalyz er; import org.apache.lucene.queryParser.ParseException;
1
2219
by: basm101 | last post by:
Hello, Firstly, apologies if this should be in the javascript forum - I wasnt sure which was most appropriate to post this question in... I am not sure if my problem is caused by the way I am mixing java and javascript in my jsp and if it can be fixed. If currentObservation.getComment() (java) is not null then all is well. But if it is null, instead of just setting document.commentForm.commentBox.value to a blank string I get a...
1
1258
by: Andryanus | last post by:
Hello everyone, Does anyone have experience accessing Java Jar Object with ASP? Please kindly advise. Thank you.
13
8936
by: geosmy | last post by:
Hi everyone, First post here! I have been trying to upgrade to Acc2007 looking forward to using Split Forms. To my horror I have just discovered that Split Forms do not hold variables at module level!!! Although code is working perfectly well when in Single Form view, when switching to Split Form view... problems. This must definitely be a bug unless there are limitations to Split Forms (doubt it). Although there might be some...
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10580
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10323
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9157
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5652
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3821
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2993
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.