首页 > 解决方案 > 用数字而不是索引编辑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)中的索引号我想使用随机数来设置。如何?

标签: javaarraysarraylist

解决方案


对于一个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);
}

推荐阅读