Arraylist's Custom Contains Method

ArrayList's custom Contains method

here's some code that might demonstrate how it works out:

import java.util.ArrayList;

class A {
private Long id;
private String name;

A(Long id){
this.id = id;
}

@Override
public boolean equals(Object v) {
boolean retVal = false;

if (v instanceof A){
A ptr = (A) v;
retVal = ptr.id.longValue() == this.id;
}

return retVal;
}

@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
}

public class ArrayList_recap {
public static void main(String[] args) {
ArrayList<A> list = new ArrayList<A>();

list.add(new A(0L));
list.add(new A(1L));

if (list.contains(new A(0L)))
{
System.out.println("Equal");
}
else
{
System.out.println("Nah.");
}
}

}

First, there is an override of the equals(Object o) method. Then there is the override of the hashCode() as well. Also note that the instanceof A check in the equals will ensure that you're not trying to compare different objects.

That should do the trick! Hope it helped! Cheers :)

ArrayList's contains() method always returns false with custom object

Your equals implementation is incorrect. equals has a specific contract; that code attempts to violate that contract. From the documentation:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

There's no way to make an instance of your Sign class equals to a string.

How To Use Contains on Custom Type ArrayList in java?

Overriding equals method in java is a good point as JavaProgrammer12 said.

Here is an simple example for this case.

static class DataType {

String Name;
int Age;

public DataType(String name, int age) {
Name = name;
Age = age;
}

public DataType(String name) {
Name = name;
}

@Override
public boolean equals(Object fromObj) {
DataType dt = (DataType)fromObj;

if(Name == null) return false;
if(dt.Age == Age) return true;
if(dt.Name.equals(Name)) return true;

return false;
}
}

And you can test with the class in a main.
For example,

static void containsName1(List<DataType> dtArrayLst, Scanner sc) {
System.out.print("Search Nme1 : ");

String name = sc.nextLine();
if (dtArrayLst.contains(new DataType(name))) {
System.out.println("Find");
}

System.out.println();
}

static void containsName2(List<DataType> dtArrayLst, Scanner sc) {
System.out.print("Search Nme2 : ");

String name = sc.nextLine();

System.out.print("Search age: ");
String age = sc.nextLine();

if (dtArrayLst.contains(new DataType(name, Integer.parseInt(age)))) {
System.out.println("Find");
}
System.out.println();
}

public static void main(String[] args) {
String name = "tommybee";
String age = "100";

List<DataType> dtArrayLst = new ArrayList<DataType>();

dtArrayLst.add(new DataType(name, Integer.parseInt(age)));

Scanner sc = new Scanner(System.in);

containsName1(dtArrayLst, sc);
containsName2(dtArrayLst, sc);

sc.close();
}

There is a good reference site if you want to learn about overriding equals method.

https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

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

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.

How do I use contains to search through a custom object ArrayList for a particular string?

You can use contains. But, for the first day of programming, it might be more understandable to simply iterate over your inventory, comparing the input string with the video name:

    boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line3.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");

How does a ArrayList's contains() method evaluate objects?

ArrayList implements the List Interface.

If you look at the Javadoc for List at the contains method you will see that it uses the equals() method to evaluate if two objects are the same.



Related Topics



Leave a reply



Submit