18

I have an Arraylist. If user enter the same number secondly I want to show to user. For this I need to find Arraylist have it or not.

I hope I made myself clear.

2
  • 1
    Would you like to share anything that you have tried so far? Commented Feb 18, 2012 at 16:25
  • 2
    Take a look at ArrayList API before asking such a question. It's trivial to notice ArrayList class has a contains() method from its definition. Commented Feb 18, 2012 at 16:34

4 Answers 4

51

If you are checking to see if some value is stored in an ArrayList you can use the contains() method, this will return true if the object is in the list, false otherwise.

ArrayList<Integer> intList = new ArrayList<>();

intList.add(5);
intList.add(7);
intList.add(3);
intList.add(-2);

intList.contains(-1); //returns false
intList.contains(3); //returns true
Sign up to request clarification or add additional context in comments.

Comments

6

You might want to use ArrayList.contains() to check if the element is in the ArrayList or not.

Comments

1

No, you have not. But here's my best guess:

List<Integer> values = Arrays.asList( 1, 2, 4, -5, 44 );
int userValue = 44;
if (!values.contains(userValue)) {
    values.add(userValue);
}

4 Comments

Why wouldn't you just write if (!values.contains(userValue))?
I'm not looking to "boost my rep," whatever that's supposed to mean. I'm just looking to help people reading this question in the future, since people do read old questions.
Code's not wrong. Saves one line. Who'd you help?
Really not sure why you're getting so worked up about this, but if you really want me to reply: Unless you're planning to reuse containsUserValue somewhere else, declaring a boolean like this is pointless and impedes readability, since it's yet another variable for the reader to keep track. Don't worry, it's a common stylistic error.
0

If I understand your question, you want to check if an array list already contains and integer value. If so, you could use ArrayList.contains().

Sample code here:

ArrayList list = new ArrayList();
int x = 4, y = 7;
int z = x;

list.add(x);

//List contains the value 4, which is the value stored in z
//Program will output "List contains 4"
if(list.contains(z))
{
    System.out.printf("List contains %d\n", z);
}
else
{
    System.out.printf("List does not contain %d\n", z);
}

//List contains the value 7, which is the value stored in y
//Program will output "List does not contain 7"   
if(list.contains(y))
{
    System.out.printf("List contains %d\n", y);
}
else
{
    System.out.printf("List does not contain %d\n", y);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.