How to change value of ArrayList element in java

前端 未结 7 1883
清酒与你
清酒与你 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:14

    I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator

    ListIterator i = a.listIterator();
    //changed the value of first element in List
    Integer x =null;
            if(i.hasNext()) {
                x = i.next();
                x = Integer.valueOf(9);
            }
        //set method sets the recent iterated element in ArrayList
        i.set(x);
            //initialized the iterator again and print all the elements
            i = a.listIterator();
            while(i.hasNext())
            System.out.print(i.next());
    

    But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection

提交回复
热议问题