How to change value of ArrayList element in java

前端 未结 7 1855
清酒与你
清酒与你 2020-12-02 09:57

Please help me with below code , I get the same output even after changing the value

import java.util.*;

class Test {
    public static void main(String[] a         


        
相关标签:
7条回答
  • 2020-12-02 10:33

    Where you say you're changing the value of the first element;

    x = Integer.valueOf(9);
    

    You're changing x to point to an entirely new Integer, but never using it again. You're not changing the collection in any way.

    Since you're working with ArrayList, you can use ListIterator if you want an iterator that allows you to change the elements, this is the snippet of your code that would need to be changed;

    //initialize the Iterator
    ListIterator<Integer> i = a.listIterator();

    //changed the value of frist element in List
    if(i.hasNext()) {
        i.next();
        i.set(Integer.valueOf(9));    // Change the element the iterator is currently at
    }

    // New iterator, and print all the elements
    Iterator iter = a.iterator();
    while(iter.hasNext())
        System.out.print(iter.next());

    >> 912345678

    Sadly the same cannot be extended to other collections like Set<T>. Implementation details (a HashSet for example being implemented as a hash table and changing the object could change the hash value and therefore the iteration order) makes Set<T> a "add new/remove only" type of data structure, and changing the content at all while iterating over it is not safe.

    0 讨论(0)
提交回复
热议问题