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));
}
}
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]
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");
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);
}
}
I have a ListView with an arraylist with an unknown number of string elements. I want to change/modify every single one of these string items. The problem is that i dont know how many items there are since the user can change it.
I have a translate function that takes a string and returns a string. What i want to do is
arraylistelement1 = translate(arraylistelement1);
arraylistelement2 = translate(arraylistelement2);
...
and repopulate the listview arraylist with the new strings.
Whats a way to do this?
Iterate over the list and create a new list of translated options from the original then replace the contents of the original list with the new values. If you do the replacing while iterating you'll get ConcurrentModificationExceptions.
Use ListIterator.set:
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("s0", "s1", "s2"));
ListIterator<String> iter = list.listIterator();
while (iter.hasNext())
iter.set(translate(iter.next()));
for (String element : list)
System.out.println(element);
}
public static String translate(String element) {
return element + " " + Math.random();
}
Is there a method in Java to get the list of objects from an Arraylist to another ArrayList, by just specifying the start and end index?
Yes you can use the subList method:
List<...> list2 = list1.subList(startIndex, endIndex);
This returns a view on that part of the original list, it does not copy the data.
If you want a copy:
List<...> list2 = new ArrayList<...> (list1.subList(startIndex, endIndex));
/create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To get a sub list of Java ArrayList use
List subList(int startIndex, int endIndex) method.
This method returns an object of type List containing elements from
startIndex to endIndex - 1.
*/
List lst = arrayList.subList(1,3);
//display elements of sub list.
System.out.println("Sub list contains : ");
for(int i=0; i< lst.size() ; i++)
System.out.println(lst.get(i));
I know that for arrays you can add an element in a two dimensional array this way:
array[0][1] = 17; //just an example
How can I do the same thing with ArrayList?
myList.get(0).set(1, 17);
maybe?
This assumes a nested ArrayList, i.e.
ArrayList<ArrayList<Integer>> myList;
And to pick on your choice of words: This assigns a value to a specific place in the inner list, it doesn't add one. But so does your code example, as arrays are of a fixed size, so you have to create them in the right size and then assign values to the individual element slots.
If you actually want to add an element, then of course it's .add(17), but that's not what your code did, so I went with the code above.
outerList.get(0).set(1, 17);
with outerList being a List<List<Integer>>.
Remember that 2-dimensional arrays don't exist. They're in fact arrays or arrays.
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
data.add(new ArrayList<String>());
data.get(0).add("String");
ArrayList<ArrayList<String>> contains elements of type ArrayList<String>
Each element must be initialised
These elements contain elements of type String
To get back the String "String" in the 3-line example, you would use
String getValue = data.get(0).get(0);
the way i found best and convinient for me was to declare ur 2d arrayList and then also a nornal mono-dimension array.
ArrayList<ArrayList<String>> 2darraylist = new ArrayList<>();
ArrayList<String> 1darraylist=new ArrayList<>();
then fill the '1D'array list and later add the 1D to the 2D array list.
1darraylist.add("string data");
2darraylist.add(idarraylist);
this will work as long as your problem is simply to add to elements to the list. if u want to add them to specific positions in the list, the the .get().set(); is what u wanna stick to.
ArrayList<ArrayList<Integer>> FLCP = new ArrayList<ArrayList<Integer>>();
FLCP.add(new ArrayList<Integer>());
FLCP.get(0).add(new Integer(0));
Each element must be instantiated. Here the outer ArrayList has ArrayList element, and first you need to add an element to reference it using get method.
Some additional notes; after reading other answers and comments:
1> Each element must be instantiated; initialization is different from instantiation (refer to flexJavaMysql's answer)
2> In Java, 2-dimensional arrays do exist; C# doesn't have 2D arrays (refer to JB Nizet's answer)
String[] myList = {"a","b","c","d"};
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
data.add(new ArrayList<String>());
int outerIndex =0;
int innerIndex =0;
for (int i =0; i<list.length; i++) {
data.get(outerIndex).add(innerIndex, list[i]);
innerIndex++;
}
System.out.println(data);
Simple for loop to add data to a multidimensional Array.
For every outer index you need to add
data.add(new ArrayList<String>());
then increment the outer index, and reset the inner index.
That would look something like this.
public static String[] myList = {"a", "b","-","c","d","-","e","f","-"};
public static ArrayList<ArrayList<String>> splitList(String[] list) {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
data.add(new ArrayList<String>());
int outerIndex =0;
int innerIndex =0;
for (int i=0; i<list.length; i++) {
System.out.println("will add: " + list[i]);
if(!list[i].contains("-")) {
System.out.println("outerIndex: " + outerIndex +" innerIndex: "+ innerIndex);
data.get(outerIndex).add(innerIndex, list[i]);
innerIndex++;
} else {
outerIndex++; // will move to next outerIndex
innerIndex = 0; // reset or you will be out of bounds
if (i != list.length-1) {
data.add(new ArrayList<String>()); // create an new outer index until your list is empty
}
}
}
return data;
}
public static void main(String[] args) {
System.out.println(splitList(myList));
}
I think it's a fairly simple question, but I can't figure out how to do this properly.
I've got an empty arraylist:
ArrayList<object> list = new ArrayList<object>();
I've got some objects In which I want to add object and each object has to be at a certain position. It is necessary however that they can be added in each possible order. When I try this, it doesn't work and I get an IndexOutOfBoundsException:
list.add(1, object1)
list.add(3, object3)
list.add(2, object2)
What I have tried is filling the ArrayList with null and then doing the above. It works, but I think it's a horrible solution. Is there another way to do this?
You can do it like this:
list.add(1, object1)
list.add(2, object3)
list.add(2, object2)
After you add object2 to position 2, it will move object3 to position 3.
If you want object3 to be at position3 all the time I'd suggest you use a HashMap with position as key and object as a value.
You can use Array of objects and convert it to ArrayList-
Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";
List<Object> list= Arrays.asList(array);
ArrayList will be- [1, null, 2, 3, null, null, null, 7, null, null]
If that's the case then why don't you consider using a regular Array, initialize the capacity and put objects at the index you want.
Object[] list = new Object[10];
list[0] = object1;
list[2] = object3;
list[1] = object2;
You could also override ArrayList to insert nulls between your size and the element you want to add.
import java.util.ArrayList;
public class ArrayListAnySize<E> extends ArrayList<E>{
#Override
public void add(int index, E element){
if(index >= 0 && index <= size()){
super.add(index, element);
return;
}
int insertNulls = index - size();
for(int i = 0; i < insertNulls; i++){
super.add(null);
}
super.add(element);
}
}
Then you can add at any point in the ArrayList. For example, this main method:
public static void main(String[] args){
ArrayListAnySize<String> a = new ArrayListAnySize<>();
a.add("zero");
a.add("one");
a.add("two");
a.add(5,"five");
for(int i = 0; i < a.size(); i++){
System.out.println(i+": "+a.get(i));
}
}
yields this result from the console:
0: zero
1: one
2: two
3: null
4: null
5: five
I draw your attention to the ArrayList.add documentation, which says it throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
Check the size() of your list before you call list.add(1, object1)
You need to populate the empty indexes with nulls.
while (arraylist.size() < position)
{
arraylist.add(null);
}
arraylist.add(position, object);
#Maethortje
The problem here is java creates an empty list when you called new ArrayList and
while trying to add an element at specified position you got IndexOutOfBound ,
so the list should have some elements at their position.
Please try following
/*
Add an element to specified index of Java ArrayList Example
This Java Example shows how to add an element at specified index of java
ArrayList object using add method.
*/
import java.util.ArrayList;
public class AddElementToSpecifiedIndexArrayListExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
/*
To add an element at the specified index of ArrayList use
void add(int index, Object obj) method.
This method inserts the specified element at the specified index in the
ArrayList.
*/
arrayList.add(1,"INSERTED ELEMENT");
/*
Please note that add method DOES NOT overwrites the element previously
at the specified index in the list. It shifts the elements to right side
and increasing the list size by 1.
*/
System.out.println("ArrayList contains...");
//display elements of ArrayList
for(int index=0; index < arrayList.size(); index++)
System.out.println(arrayList.get(index));
}
}
/*
Output would be
ArrayList contains...
1
INSERTED ELEMENT
2
3
*/
How about this little while loop as a solution?
private ArrayList<Object> list = new ArrayList<Object>();
private void addObject(int i, Object object) {
while(list.size() < i) {
list.add(list.size(), null);
}
list.add(i, object);
}
....
addObject(1, object1)
addObject(3, object3)
addObject(2, object2)
This is a possible solution:
list.add(list.size(), new Object());
I think the solution from medopal is what you are looking for.
But just another alternative solution is to use a HashMap and use the key (Integer) to store positions.
This way you won't need to populate it with nulls etc initially, just stick the position and the object in the map as you go along. You can write a couple of lines at the end to convert it to a List if you need it that way.
Bit late but hopefully can still be useful to someone.
2 steps to adding items to a specific position in an ArrayList
add null items to a specific index in an ArrayList
Then set the positions as and when required.
list = new ArrayList();//Initialise the ArrayList
for (Integer i = 0; i < mItems.size(); i++) {
list.add(i, null); //"Add" all positions to null
}
// "Set" Items
list.set(position, SomeObject);
This way you don't have redundant items in the ArrayList i.e. if you were to add items such as,
list = new ArrayList(mItems.size());
list.add(position, SomeObject);
This would not overwrite existing items in the position merely, shifting existing ones to the right by one - so you have an ArrayList with twice as many indicies.
You should set instead of add to replace existing value at index.
list.add(1, object1)
list.add(2, object3)
list.set(2, object2)
List will contain [object1,object2]
Suppose you want to add an item at a position, then the list size must be more than the position.
add(2, item): this syntax means, move the old item at position 2 to next index and add the item at 2nd position.
If there is no item in 2nd position, then this will not work, It'll throw an exception.
That means if you want to add something in position 2,
your list size must be at least (2 + 1) =3, so the items are available at 0,1,2 Position.
in that way it is ensured that the position 2 is accessed safely and there would be no exception.
If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map