Arraylist - 设置/添加方法使用 - Java [英] Arraylist - Set/ add method usage - Java

查看:26
本文介绍了Arraylist - 设置/添加方法使用 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组列表.我的要求是确定 arraylist 是否有一个元素存在于指定的索引处.如果是,则应为该索引设置一个值(使用 set 方法),否则应向该索引添加一个值索引位置(使用add方法)

I have an Arraylist of integers. My requirement is to determine if the arraylist HAS an element existing at the specified index.If YES, then a value should be set to that index (using set method), else a value should be added to that index location(using add method)

发现在我的 java 代码中处理上述情况有点困难.请帮忙.

Finding it a bit difficult to handle the above condition in my java code.Please help.

这是我目前所拥有的:

    ArrayList<Integer> tempArray = new ArrayList<Integer>();
        int counter = 0;
        int tempValue = 0;
    For LOOP -
      if (//certain conditions are satisfied){

      tempValue = calculateNewValue();
      tempArray.add(counter, tempValue); //Need some logic here to determine if its a set or add method to be used
    }
if (//some other conditions are satisfied){
       counter++;
}
    end For LOOP

推荐答案

set 方法用新元素替换指定位置的元素.但是在 add(position, element) 中将添加指定位置的元素并将现有元素移动到数组的右侧.

set method replaces the element in the specified position with the new element. But in add(position, element) will add the element in the specified position and shifts the existing elements to right side of the array .

ArrayList<String> al = new ArrayList<String>();

    al.add("a");
    al.add(1, "b");
    System.out.println(al);

    al.set(0, "c");
    System.out.println(al);

    al.add(0, "d");
    System.out.println(al);

---------------输出 -------------------------------------

---------------Output -------------------------------------

[a, b]

[c, b]

[d, c, b]

这篇关于Arraylist - 设置/添加方法使用 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆