java - 用数字而不是索引编辑arraylist
问题描述
如何使用值而不是索引号编辑数组列表?使用 arraylist.set( 93, 92)
ArrayList al = new ArrayList();
Random rand = new Random();
Scanner sc = new Scanner(System.in);
//Generates arraylsit with size 10 with random integers from 1 to 100
for (int j = 0; j<10; j++)
{
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("Please enter an integer to update or edit: ");
int toUpdateInt = sc.nextInt();
System.out.println("Please eneter the new value of data: ");
int newValue = sc.nextInt();
al.set(toUpdateInt, newValue);
System.out.println(al);
在我的代码中,它要求(toUpdateInt)中的索引号我想使用随机数来设置。如何?
解决方案
对于一个Set
(没有重复,没有顺序),这将是快速和容易的。
Set<Integer> al = new HashSet<>();
Random rand = new Random();
for (int j = 0; j < 10; j++)
{
int pick = rand.nextInt(100);
al.add(pick);
}
...
al.remove(toUpdateInt);
al.add(newValue);
对于一个List
:
List<Integer> al = new ArrayList<>();
int index = al.indexOf(toUpdateInt);
if (index != -1) {
al.set(index, newValue);
}
推荐阅读
- tsql - 将 Numeric(19,0) 值转换为 DateTime
- java - JPanel 不遵守 setMinimumSize / ComponentListener
- python - 如何让演员从屏幕的右侧滑出然后重置回左侧
- python - 如何在 tkinter python 中禁用复选框的动画
- arrays - 对文档中的值求和
- orbeon - 如何将导航与使用表单生成器创建的 orbeon 表单一起使用?
- linux - top 通过命令行选项添加过滤器命令
- android - Room - 在运行时(在用户端)添加或删除列?
- java - JSON对象数组到Java POJO
- java - 如何在 antlr4 访问者方法中抛出异常?