How do I iterate and modify Java Sets?

前端 未结 5 1384
既然无缘
既然无缘 2020-12-13 03:19

Let\'s say I have a Set of Integers, and I want to increment every Integer in the Set. How would I do this?

Am I allowed to add and remove elements from the set whi

5条回答
  •  醉梦人生
    2020-12-13 04:00

    You could create a mutable wrapper of the primitive int and create a Set of those:

    class MutableInteger
    {
        private int value;
        public int getValue()
        {
            return value;
        }
        public void setValue(int value)
        {
            this.value = value;
        }
    }
    
    class Test
    {
        public static void main(String[] args)
        {
            Set mySet = new HashSet();
            // populate the set
            // ....
    
            for (MutableInteger integer: mySet)
            {
                integer.setValue(integer.getValue() + 1);
            }
        }
    }
    

    Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.

提交回复
热议问题