Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: to use contains in a ArrayList full of custom object should I override equals or implement Comparable/Comparator?

Tags:

I have an ArrayList full of these:

class TransitionState {

    Position positionA;
    Position positionB;

    int counter;

    public boolean equals (Object o){

        if (o instanceof TransitionState){

          TransitionState transitionState= (TransitionState)o;

          if ((this.positionA.equals(transitionState.positionA))
                  &&(this.positionB.equals(transitionState.positionB)))
          {
              return true;
          }
        }
     return false;

    }

    @Override
    public String toString() {

        String output = "Position A " + positionA.i+ " "+ positionA.j + " "+ positionA.orientation + " "+
                "Position B " + positionB.i + " "+ positionB.j + " "+ positionB.orientation;

        return output;
    }

}

class Position {

    int i;
    int j;
    char orientation;

    Position() {

    }


    void setIJ(int i, int j){
        this.i=i;
        this.j=j;
    }

    void setOrientation(char c){

        orientation = c;
    }

   public boolean equals(Object o){

        if(o instanceof Position){

          Position p = (Position)o;
          if((p.i==this.i)&&(p.j==this.j)&&(p.orientation==this.orientation))
          {
              return true;
          }
              else return false;

        }

            return false;
   }

} //end class Position

I query it with this:

 if(!transitionStatesArray.contains(newTransitionState)){  //if the transition state is new add and enqueue new robot positions

                 transitionStatesArray.add(newTransitionState); //marks as visited

I'm finding duplicate elements inside my transitionStatesArray, why is this?

I'm using these i,j and orientation values to fill unique values in a matrix, yet here I have a duplicate:

 S  .  N 
 *  *  * 
 .  D  D 


 E  .  O 
 *  *  * 
 .  D  D 


 N  .  S 
 *  *  * 
 .  D  D 


 S  .  N 
 *  *  * 
 .  D  D 
like image 727
andandandand Avatar asked May 06 '11 05:05

andandandand


People also ask

Can I use contains for ArrayList?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

Can we use comparator with ArrayList?

Using Comparator we can sort ArrayList on the basis of multiple variables. We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface.

Does ArrayList contain equals in Java?

It uses equals, not ==. The source comes with the JDK, remember: ?

How do you use contains in a list of objects?

To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.


1 Answers

The List.contains(...) method is defined to use equals(Object) to decide if the argument object is "contained" by the list. So you need to override equals ... assuming that the default implementation is not what you need.

However, you need to be aware that List.contains(...) potentially tests the argument against every element in the list. For a long list, that's expensive. Depending on the details of your application, it may be better to use a different collection type (e.g. a HashSet, TreeSet or LinkedHashSet) instead of a List. If you use one of those, your class will need to override hashCode or implement Comparable, or you will need to create a separate Comparator ... depending on what you choose.


(A bit more advice on the alternatives ... since the OP is interested)

The performance of contains on a List type like ArrayList or LinkedList is O(N). The worst-case cost of a contains call is directly proportional to the list length.

For a TreeSet the worst-case performance of contains is proportional to log2(N).

For a HashSet or LinkedHashSet, the average performance of contains is a constant, independent of the size of the collection, but the worst-case performance is O(N). (The worst case performance occurs if you 1) implement a poor hashcode() function that hashes everything to a small number of values, or 2) tweak the "load factor" parameter so that the hash table doesn't automatically resize as it grows.)

The downside of using Set classes are:

  • they are sets; i.e. you cannot put two or more "equal" objects into the collection, and
  • they can't be indexed; e.g. there's no get(pos) method, and
  • some of the Set classes don't even preserve the insertion order.

These issues need to be considered when deciding what collection class to use.

like image 62
Stephen C Avatar answered Oct 29 '22 00:10

Stephen C