E
E
er122015-04-29 11:13:15
Java
er12, 2015-04-29 11:13:15

How to search for an element in a List?

I have data type T - Integer, String
List a. how do i check if a contains the number 17 without considering the value of String

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bromzh, 2015-04-29
@bromzh

The questions need to be more precise. Since nifiga is not clear how your classes are arranged. There is no such type T, this letter usually denotes a parameterized type.
If you just need to find out if an object exists or not, then no parameterization is required:

public class Foo {

    static List<Object> list = new LinkedList<>();

    public static boolean hasElem(Object elem) {
        for (Object item : list) {
            if (Objects.equals(item, elem)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {

        list.add(1);
        list.add("s1");
        list.add(2);
        list.add("s2");
        list.add(3);
        list.add("s3");

        if (hasElem(3)) {
            System.out.println("Has elem 3");
        }
        if (hasElem("s2")) {
            System.out.println("Has elem \"s2\"");
        }
        if (hasElem('c')) {
            System.out.println("Has elem 'c'");
        }
    }
}

If you parametrize your class/method with type T, then you don’t need to check anything: when you create an instance of such a class, parameterized with type String , then the list will be only from strings and the search will be by strings. When you parameterize it with Integer , there will be numbers everywhere.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question