2012-02-18 38 views
9

我有一个Arraylist。如果用户第二次输入相同的号码,我想向用户显示。为此,我需要找到Arraylist有没有。我需要在arraylist中找到一个整数数据?

我希望我明确自己。

+1

你想分享什么,你到目前为止试过吗? – dasblinkenlight 2012-02-18 16:25:57

+2

在问这样一个问题之前,先看看ArrayList API。注意到ArrayList类的定义中有一个contains()方法,这很简单。 – Juvanis 2012-02-18 16:34:07

回答

25

如果要检查看,如果某个值存储在ArrayList可以使用方法,这将返回true如果对象是在列表中,false否则。

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 
+0

很好的答案!谢谢。 – 2017-03-24 05:03:42

0

不,你没有。但这里是我最好的猜测:

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

为什么不直接写'if(!values.contains(userValue))'? – user3932000 2018-01-13 21:25:29

+0

可以做到这一点。没有增加太多价值,特别是在问题首次被问到六年后。找到一个更好的方法来提升你的代表。 – duffymo 2018-01-13 22:28:43

+0

我不打算“提高我的代表”,无论这应该是什么意思。我只是想帮助人们在将来阅读这个问题,因为人们*会阅读旧的问题。 – user3932000 2018-01-13 23:01:02

0

如果我理解你的问题,你想检查一个数组列表是否已经包含整数值。如果是这样,你可以使用ArrayList.contains()。

示例代码浏览:

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); 
} 
相关问题