The Artima Developer Community
Sponsored Link

Java Answers Forum
Simple array equality question (hopefully!)

1 reply on 1 page. Most recent reply: Oct 8, 2004 5:17 PM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Guido

Posts: 38
Nickname: kiethb
Registered: May, 2002

Simple array equality question (hopefully!) Posted: Oct 8, 2004 6:54 AM
Reply to this message Reply
Advertisement
can someone tell me why the following doesn't work?

public class AryTest{
 
	static String[] str = {"Java ","is ", "great!"};
	static String[] str2 = {"Java ","is ","great!"};
 
        public static void main(String[] args){
 
        if(str.equals(str2)){
	     System.out.println("they are equal!");
	}
	else{
		System.out.println("they are not equal!");
		}


I know that if I import the Arrays class and do a test like:

if(Arrays.equals(str,str2))

that will work, I just need to know why the other doesn't work and/or why if its not testing anything useful that it doesn't throw a compile error.

thank you


Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: Simple array equality question (hopefully!) Posted: Oct 8, 2004 5:17 PM
Reply to this message Reply
An array in Java is an object. Here, str and str2 are two different objects. By default, equals() method compares the references to two objects. It returns true only if two objects being compared are same. That is, o1.equals(o2) is same as o1 == o2 unless the class of o1 overrides the equals() method. Since array object's class is built-in class types, we cannot override array class equals() method. So, you will have to accept the default behaviour. That is, str.euals(str2) is same as saying str == str2. And, you know that str is certainly not same as str2.

Flat View: This topic has 1 reply on 1 page
Topic: To Senthoorkumaran Previous Topic   Next Topic Topic: JSF Application in Jakarta Pluto

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use