0

I have two lists one is feature and has a placement number based on which i insert data in sorted list e.g if placement number is 5 data will be added in 5th position .i want to add data at 5th postion and to move data which was at 5th position to next index but in my case it just replace data at 5th position not move current data to next position

      for (int i = 0; i < featuredList.size(); i++) {

            int n = featuredList.get(i).getPlacementNumber().intValue();
            if (n < sortedList.size()) {

                    sortedList.add(n, featuredList.get(i));


            } else {
                sortedList.add(featuredList.get(i));
            }


        }
3

3 Answers 3

3

You should use ArrayList, from add(int index, E element)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Make your sortedList as ArrayList:

List<YourType> sortedList= new ArrayList<YourType>();

See the example http://ideone.com/L6hpsf

String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
List<String> list = new ArrayList<String>();
list.add(s1);
list.add(s3);
list.add(1, s2);
System.out.println(list);

Output: [s1, s2, s3]

Sign up to request clarification or add additional context in comments.

2 Comments

i have initialed but it replace data at index instead of adding data at a given index and moving the data to next index
Can you give use example and output/expected value of your program?
1

Try to use LinkedList to insertion or deletion between list for better performance then ArrayList :

private LinkedList<String> linkedList = new LinkedList<String>();

linkedList.add("1");
linkedList.add("2");
linkedList.add("3");
linkedList.add("4");
linkedList.add("5");

// insertion at 3 position
linkedList.add(2,"6");

Comments

0

Another example which may give you some clue and even easy to run :)

import java.util.ArrayList;


public class Alisttest {
  public static void main(String[] args) {
    ArrayList a = new ArrayList();
    a.add("1");
    a.add("2");
    a.add("3");
    a.add("4");


    System.out.println("a=> "+a.get(2));
    a.add(2, "Pankaj");

    System.out.println("a=> "+a.get(2));
    System.out.println();
    System.out.println("a=> "+a);
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.