Results 1 to 4 of 4
Thread: Why aren't my arrays equal?
- 10-10-2011, 04:41 AM #1
Member
- Join Date
- Oct 2011
- Posts
- 3
- Rep Power
- 0
Why aren't my arrays equal?
I'm writing a code and one of the problems I came across is that reading from a file and actually imputing values will not give the same result. I created this code to simulate my problem:
Java Code:import java.io.*; import java.util.Scanner; public class test { public static void main (String [] args)throws IOException{ File filename = new File(args[0]); //I created a file "data" that contains "Hi" Scanner scan = new Scanner(filename); String []test1 = new String [1]; String []test2 = new String [1]; for(int i=0;i<test1.length;i++) test1[i]=scan.next(); test2[0]="Hi"; if(test2[0]==test1[0]) System.out.println("Hi"); else System.out.println("fail"); } }
OUTPUT
fail
I'm not exactly sure why this is so if someone could tell me why it's like this and how to fix this problem i would appreciate it.
- 10-10-2011, 04:55 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Re: Why aren't my arrays equal?
Strings - and other objects - should be compared using the equals() method and not ==.
The point is that all classes define "equals" in a way that makes sense for them. In the case of strings what you want to do is see if they are made up of the same characters in the same order, which is what test2[0].equals(test1[0]) does. This is not the same thing as ==, which is more like "identical". For instance, the third word in this sentence is equal to the 12th but they are not identical because the sentence contains twenty eight words not twenty seven.
- 10-10-2011, 05:03 AM #3
Member
- Join Date
- Oct 2011
- Posts
- 3
- Rep Power
- 0
Re: Why aren't my arrays equal?
Ah thank you so much I completely forgot about the equals() method!
- 10-10-2011, 06:46 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,716
- Rep Power
- 19
Similar Threads
-
comparing 2 arrays to see if they're equal
By Get_tanked in forum New To JavaReplies: 2Last Post: 02-17-2011, 07:59 AM -
Downloaded images aren't viewable
By pietertje in forum New To JavaReplies: 12Last Post: 07-05-2010, 03:56 PM -
so whats going on? (things aren't showing up)
By Adrien in forum AWT / SwingReplies: 9Last Post: 02-20-2010, 08:22 PM -
Any reason why half of components aren't drawing?
By martypapa in forum Java 2DReplies: 4Last Post: 02-17-2010, 11:17 PM
Bookmarks