Showing posts with label Method. Show all posts
Showing posts with label Method. Show all posts

Wednesday, December 28, 2016

java: difference between == and equals() with examples

Both "==" and "equals()" are used to check if two things equal to each other.

The "==" is an operator which can be used to compare primitives as well as Objects. It checks if the two items reference to the same memory location. Since it is an operator, it cannot be overridden.

The "equals()" is a method in the Object class. The "equals()" method in the Object class works the same as the "==" operator. However, since it is a method, it can be overridden to compare based on object components or business logic. As in the case of ArrayList, the equals method compares if the two ArrayLists have the same sequence of objects.

Below are some examples.

1. The String class

The String class is peculiar for it can be initiated with a string constant or a new String instance. Two String constants with the same sequence of characters are always equal regardless of using "==" or "equals()". However, it is a good practice to use equals when comparing two Strings.

String strA = "Welcome!";
String strB = "Wel" + "come!";
String strC = new String(strA);
String strD = new String("Welcome!");

System.out.println("strA == strB? " + (strA == strB));
System.out.println("strA.equals(strB)? " + (strA.equals(strB)));
System.out.println("strA == strC? " + (strA == strC));
System.out.println("strA.equals(strC)? " + (strA.equals(strC)));
System.out.println("strC == strD? " + (strC == strD));
System.out.println("strC.equals(strD)? " + (strC.equals(strD)));

The output:
strA == strB? true
strA.equals(strB)? true
strA == strC? false
strA.equals(strC)? true
strC == strD? false
strC.equals(strD)? true

2. Without overriding the equals() method

public class ObjA {
   private ArrayList<String> array;
   private int numb;

   public ObjA() {
        array = new ArrayList<>();
        numb = 3;
   }
 
   public static void main(String[] args) {
        ObjA theFirst = new ObjA();
        ObjA theSecond = new ObjA();
        ObjA theThird = theFirst;

        System.out.println("Is theFirst == theSecond? " + (theFirst == theSecond));
        System.out.println("Is theFirst.equals(theSecond)? " + (theFirst.equals(theSecond)));
        System.out.println("Is theFirst == theThird? " + (theFirst == theThird));
        System.out.println("Is theFirst.equals(theThird)? " + (theFirst.equals(theThird)));
        System.out.println("Is theSecond == theThird? " + (theSecond == theThird));
        System.out.println("Is theSecond.equals(theThird)? " + (theSecond.equals(theThird)));
   }
}

The Outpput:
Is theFirst == theSecond? false
Is theFirst.equals(theSecond)? false
Is theFirst == theThird? true
Is theFirst.equals(theThird)? true
Is theSecond == theThird? false
Is theSecond.equals(theThird)? false

3. With overriding the equals() method

public class ObjB {
   private ArrayList<String> array;
   private int numb;

   public ObjB() {
        array = new ArrayList<>();
        numb = 3;
   }

   public ArrayList getArray() {
         return array;
   }

   public int getNumber() {
         return numb;
   }

   @Override
   public boolean equals(Object obj) {
         if (obj instancdof ObjB){
              ObjB ob = (ObjB)obj;
              if (getArray().equals(ob.getArray()) && getNumber() == ob.getNumber()){
                   return true;
              }
         }
         return false;
   }
 
   public static void main(String[] args) {
        ObjB theFirst = new ObjB();
        ObjB theSecond = new ObjB();
        ObjB theThird = theFirst;

        System.out.println("Is theFirst == theSecond? " + (theFirst == theSecond));
        System.out.println("Is theFirst.equals(theSecond)? " + (theFirst.equals(theSecond)));
        System.out.println("Is theFirst == theThird? " + (theFirst == theThird));
        System.out.println("Is theFirst.equals(theThird)? " + (theFirst.equals(theThird)));
        System.out.println("Is theSecond == theThird? " + (theSecond == theThird));
        System.out.println("Is theSecond.equals(theThird)? " + (theSecond.equals(theThird)));
   }
}

The Outpput:
Is theFirst == theSecond? false
Is theFirst.equals(theSecond)? true
Is theFirst == theThird? true
Is theFirst.equals(theThird)? true
Is theSecond == theThird? false
Is theSecond.equals(theThird)? true

---------------------------------------------------------------------------------------------------

                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, December 27, 2013

Use reflection to dynamically invoke methods

This sample code uses class reflection associated with an ActionListener to dynamically invoke the specified method at runtime. The method name and parameters can be set differently under different conditions and for different source objects.

In the code, class MethodRelection has three JTextField fields and an objModified method. When any of the JTextField fields is modified, the objModified method will be called to handle the modification accordingly.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MethodReflection extends JFrame{
    public MethodReflection() {
        JTextField[] data = {new JTextField("Peach", 20),
                                  new JTextField("Papaya", 20),
                                  new JTextField("Mango", 20)};
        JPanel panel = new JPanel(new GridLayout(3, 1));
     
        for (int i=0; i<data.length; i++){
            try {
                data[i].addActionListener(new ObjectActionListener(this,
                                                   "objModified",
                                                   new Object[]{data[i], "Field "+(i+1)+" Modified"}
                ));
                panel.add(data[i]);
            } catch (NoSuchMethodException e){
                System.out.println(e.getMessage());
            }
        }
     
        this.add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(700, 300);
        this.pack();
    }
 
    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                (new MethodReflection()).setVisible(true);
            }
        });
     
     
    }
 
    public class ObjectActionListener implements ActionListener {
        private Object methodSource = null;
        private Object[] parameters = null;
        private String methodName = null;
        private Method method = null;

        public ObjectActionListener(Object methodSource, String methodName, Object[] parameters)
                throws NoSuchMethodException, SecurityException {
            this.methodSource = methodSource;
            this.methodName = methodName;
            if (parameters == null) {
                parameters = new Object[0];
            }
            this.parameters = parameters;
            method = getMethod();
        }

        private Method getMethod() throws NoSuchMethodException {
            Class theClass = methodSource.getClass();

            Class[] paramTypes = new Class[parameters.length];
            for (int i = 0; i < parameters.length; i++) {
                paramTypes[i] = parameters[i].getClass();
            }
            return theClass.getMethod(methodName, paramTypes);
        }

        public void actionPerformed(ActionEvent event) {
            try {
                method.invoke(methodSource, parameters);
            } catch (IllegalAccessException e) {
                System.out.println(e.getMessage());
            } catch (InvocationTargetException e) {
                System.out.println(e.getMessage());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
 
    public void objModified(JTextField obj, String message){
            String text = obj.getText();
            System.out.println(message+": "+text);
    }
}

The code using MethodHandle to dynamically invoke method can be found here

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.