I am trying to add various items in various positions in an arraylist.
I need to use arraylist as the number of elements to be read is unclear.
while I am adding elements I am getting indexoutofbonds exception.
I understand that If the index is larger than size() I may get the exception.
but since I suppose that the size will be increased when I try to add more elements than size of the arraylist, why I am getting exception? difference between array and arraylist is that arraylist is dynamic and handle size issues? Am I wrong?
An example is as follows. I am using arraylist of arraylists.
arr.add(e1,new ArrayList<Integer>());
in that case e1 may be 1,0,10001,4,540,100000
Isn't arraylist should handle that problem?
What I mean is
I don't want to use that method below. I need spaces between the elements so that other elements can fit into their locations as the program reads the data. I don't want them to be shifted as the add method specified for the above code is taking a position and element. I don't want to add the item to next available position.
arr.add(new ArrayList<Integer>());
Any help will be useful. OR you can ask me to use another data structure in Java that will help my problem.
It'll take care of the dynamically for you if you don't specify the index you want to insert. But if you want to insert at a specific position, you must be sure that:
index >= 0 && index < size()
See the documentation:
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).
..
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
According to the document,
public void add(int index,
E element)
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
You must ensure that the index is not out of range.
In other word, if you specify index which > size(), ArrayList don't know how to manipulate the elements between size() and the index. Should it construct these elements and add them for you, maybe by default constructor? I think it should be your responsibility. Such as:
if (e1 > arr.size()) {
arr.addAll(Collections.nCopies(e1 - arr.size(), Integer.valueOf(0)));
}
arr.add(e1, new ArrayList<Integer>());
Ok.I figured it out. ArrayList always shifts. You can not leave spaces between elements. That was what I was looking for.
Late answer better than never;)
Related
I have an arrayList with 30 elements. I'd like to create many sublists of 15 elements from this list. What's the efficient way of doing so?
Right now I clone the ArrayList and use remove(random) to do it, but I am sure this is too clumsy. What should I do instead?
Does Java have a "sample" function like in R?
Clarification: by sampling with no replacement I mean take at random 15 unique elements from the 30 available in the original list. Moreover I want to be able to do this repeatedly.
Use the Collections#shuffle method to shuffle your original list, and return a list with the first 15 elements.
Consider creating new list and adding random elements from current list instead of copying all elements and removing them.
Another way to do this is to create some kind of View on top of the current list.
Implement an Iterator interface that randomly generates index of element during next operation and retrieves element by index from current list.
No, Java does not have a sample function like in R. However, it is possible to write such a function:
// Samples n elements from original, and returns that list
public <T> static List<T> sample(List<T> original, int n) {
List<T> result = new ArrayList<T>(n);
for (int i = 0; i < original.size(); i++) {
if (result.size() == n)
return result;
if ((n - result.size()) >= (original.size() - i)) {
result.add(original.get(i));
} else if (Math.random() < ((double)n / original.size())) {
result.add(original.get(i));
}
}
return result;
}
This function iterates through original, and copies the current element to result based on a random number, unless we are near enough to the end of original to require copying all the remaining elements (the second if statement in the loop).
This is a basic combinatorics problem. You have 30 elements in your list, and you want to choose 15. If the order matters, you want a permutation, if it doesn't matter, you want a combination.
There are various Java combinatorics samples on the web, and they typically use combinadics. I don't know of any ready made Java libraries, but Apache Math Commons has binomial coefficient support to help you implement combinadics if you go that route. Once you have a sequence of 15 indices from 0 to 29, I'd suggest creating a read-only iterator that you can read the elements from. That way you won't have to create any new lists or copy any references.
So let say I have an array of size 10 with index range from 0 to 9.
I add a bunch of elements in and stop adding at index 6. So with array.length, I can know that the size of the array is 10, but how do I find which index contain the last value and after that is empty? Am I suppose to do a loop and stop at index == null?
I mimic an arraylist by create a dynamic array that grow when the size is full.
Arg, forgot to tell you guys, if the array is int, then the empty slots will be 0?
Use java.util.ArrayList. There you no need to think about index and it is resizable-array implementation.
At the time of array creation by default all values are null so if you do not insert any value at any index (may be at end or beginning or middle of array) it would be just null. So you should put null check to verify.
Since this is you assignment a trick is to add a variable to follow the number of elements added.
So you can have a public int size = 0 variable and change you add and remove operations to increase and decrease this variable whenever you add or remove an element.
Then in you add method you can have a simple check to see if you need to expand the array
if (size == array.length)
expandArray
I have a linked list. An item may be at several indexes of this list (e.g. index 0, index 3, and index 5). How can I find if one of these indexes is index 0; I need that because I use some formulas to calculate some values, and the formula is different if one position of the item is index 0.
You can check the first element is the object you want
if (list != null && list.size() > 0 && list.get(0).equals(element))
You can use the get method on list and the equals method on your item
list.get(0).equals(myItem);
Normally you don't want to use get(int) on a LinkedList because it's an order n traversal. But index 0 will always be at the front and is a very short traversal. :)
So let say I have an array of size 10 with index range from 0 to 9.
I add a bunch of elements in and stop adding at index 6. So with array.length, I can know that the size of the array is 10, but how do I find which index contain the last value and after that is empty? Am I suppose to do a loop and stop at index == null?
I mimic an arraylist by create a dynamic array that grow when the size is full.
Arg, forgot to tell you guys, if the array is int, then the empty slots will be 0?
Use java.util.ArrayList. There you no need to think about index and it is resizable-array implementation.
At the time of array creation by default all values are null so if you do not insert any value at any index (may be at end or beginning or middle of array) it would be just null. So you should put null check to verify.
Since this is you assignment a trick is to add a variable to follow the number of elements added.
So you can have a public int size = 0 variable and change you add and remove operations to increase and decrease this variable whenever you add or remove an element.
Then in you add method you can have a simple check to see if you need to expand the array
if (size == array.length)
expandArray
According to the docs you can insert objects an any position in a List:
The user of this interface has precise control over where in the list each element is inserted.
(source: http://download.oracle.com/javase/6/docs/api/java/util/List.html)
But the following program fails with an IndexOutOfBoundsException:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<String>();
myList.add(0, "derp");
myList.add(2, "herp");
for (String s : myList) {
System.out.println("Le string: " + s);
}
}
}
It doesn't help setting initial capacity explicitly, either (which makes some sense since the default value is 10).
Why can't I insert objects at any position as long as its index is lower than the capacity? Is the size always equal to the number of inserted elements?
You can insert an object at any valid position. Take a close look at the Javadoc for add(int, E):
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
In other words, inserting an element always increases the size of the list by 1. You can insert at either end, or in the middle... but you can't insert past the end.
The capacity of an ArrayList is effectively an implementation detail - it controls when the backing array needs to be replaced by a larger one to cope with more elements. The size of a list is the important part here - a list with capacity 100 but size 5 is still only a list of 5 elements, and so inserting at position 67 into such a list would make no sense.
List capacity is not the same as its size.
The capacity is a property of array backed lists (such ArrayList or Vector), and it is the allocated size of the backing array (that is, the maximum number of items that you could put before needing to grow the structure).
The size, as you say, is the number of elements present in the list.
Then, why wouldn't you be able to insert an element wherever you want as long as there is space for it? Simple, because the List interface does not specify how the object is backed, and you couldn't do it in something like a LinkedList; so the homogeneous (and correct) behaviour is to throw an exception when that happens.
So you have two options:
Initialize the list properly by adding a default values up to your desired size.
If null is a sensible default value for you, you can use an array directly.
myList.add(2, "herp") should be myList.add(1, "herp")
As increases the size of List is by 1,not 2.
ArrayList has two members: capacity and size
capacity is the length of the underlying array, size is the length of the array the ArrayList represents
so you have to add data in the list, so that the ArrayList itself gains the size where you want to insert data
The size of the list is Always equal to the number of the inserted elements
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
javadoc
First myList.add(0, "herp") will be inserted then it will check for size. Then, size is 1 but you are inserting at position 2.