Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi I have a list with lets say these items {30 50 5 60 90 5 80} what I want to do is for example combine the 3rd and 4th element together and have {30 50 65 90 5 80}

Could you tell me how would I do that? I am using the java linked list class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        list.add(30);
        list.add(50);
        list.add(5);
        list.add(60);
        list.add(90);
        list.add(5);
        list.add(80);
        System.out.println(list);
        combine(list, 2, 3);
        System.out.println(list);
    }
    public static void combine(List<Integer> list, int indexA, int indexB) {
        Integer a = list.get(indexA);
        Integer b = list.get(indexB);
        list.remove(indexB); // [30, 50, 5, 90, 5, 80]
        list.add(indexA, a + b); // [30, 50, 65, 5, 90, 5, 80]
        list.remove(indexB); // [30, 50, 65, 90, 5, 80]
    }
}

The output is:

[30, 50, 5, 60, 90, 5, 80]
[30, 50, 65, 90, 5, 80]

You need check nulls values for avoid NullPointerException


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...