回答
如果要檢查看,如果某個值存儲在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
很好的答案!謝謝。 – 2017-03-24 05:03:42
您可能想要使用ArrayList.contains()
來檢查元素是否在ArrayList
中。
不,你沒有。但這裏是我最好的猜測:
List<Integer> values = Arrays.asList{ 1, 2, 4, -5, 44 };
int userValue = 44;
boolean containsUserValue = values.contains(userValue);
if (!containsUserValue) {
values.add(userValue);
}
爲什麼不直接寫'if(!values.contains(userValue))'? – user3932000 2018-01-13 21:25:29
可以做到這一點。沒有增加太多價值,特別是在問題首次被問到六年後。找到一個更好的方法來提升你的代表。 – duffymo 2018-01-13 22:28:43
我不打算「提高我的代表」,無論這應該是什麼意思。我只是想幫助人們在將來閱讀這個問題,因爲人們*會閱讀舊的問題。 – user3932000 2018-01-13 23:01:02
如果我理解你的問題,你想檢查一個數組列表是否已經包含整數值。如果是這樣,你可以使用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);
}
- 1. ArrayList數據需要在JTable中表示
- 2. 我需要找到一個合適的數據結構
- 3. 我需要找到一個數據結構
- 4. Python:TypeError:需要一個整數
- 5. 我需要總結一個整數的個別數字在python
- 6. 發送只有一個整數到一個函數,需要兩個整數
- 7. 我需要有一個數據庫
- 8. Java - 我需要一個數據庫嗎?
- 9. 爲什麼我得到TypeError:需要一個整數?
- 10. 我如何找到一個整數中的9個數
- 11. 找到一個整數
- 12. Matplotilb-需要找到源數據從一個類屬性
- 13. 找到一個整數到另一個整數的百分比
- 14. 需要將整個postgreSQL數據庫加載到內存中
- 15. 如何將一個有序整數ArrayList中的元素添加到另一個整數有序ArrayList中?
- 16. 類型錯誤:一個整數需要
- 17. datetime.date:TypeError:需要一個整數。爲什麼?
- 18. web2py,TypeError:需要一個整數
- 19. Python os.popen需要一個整數?
- 20. Celery SchedulingError:需要一個整數
- 21. 的Socket程序需要一個整數
- 22. 我需要修改一個表結構,並需要找到數據庫中的特定列
- 23. 需要在java數組中找到重複的整數和它們的數量
- 24. 找到一個ArrayList中
- 25. 我需要的第一個日誌在數據庫中的Java
- 26. 需要獲得乘數,將帶來一個分的分數到一個整數
- 27. 我可以從數據文件中找到mysql版本,需要恢復數據
- 28. 我需要得到一個數組中最大的數字recursevely
- 29. 類「數據庫」未找到(在這裏需要一些幫助)
- 30. 每次我是否需要在循環中新建一個ArrayList?
你想分享什麼,你到目前爲止試過嗎? – dasblinkenlight 2012-02-18 16:25:57
在問這樣一個問題之前,先看看ArrayList API。注意到ArrayList類的定義中有一個contains()方法,這很簡單。 – Juvanis 2012-02-18 16:34:07