I want to create an ArrayList<Float> of length 350. I did this:
x = new ArrayList<Float>(350);
No i want this array to have 'zero' float value at each point. i can do this:
for (int i = 0; i< 350 ; i++){
x.add((float) 0.0);
}
So my question is if there is another way to do the same thing without iterating. I want minimum iterating to increase efficiency.
If you want efficiency I wouldn't use ArrayList or Float here. I wouldn't recommend using float even as it's precision is so poor, unless you really know what you are doing.
I suggest you use an array of double.
double[] x = new double[350]; // all 0.0
java's Collections class has a nice utility for this: nCopies. Note that this creates an immutable list, but it does exactly what you want :)
From java documentation:
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
Note the list is still empty so you have to add the elements one by one. Only capacity is changed.
I would advice you to construct another collection for instance an array and then initialize the list using that constructor:
ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
As Peter says use an array. If you want this in an array list you can use the code below. This creates an arraylist of 100 integers each with a value of 42
Integer[] a = new Integer[100];
Arrays.fill(a, 42);
List<Integer> l = new ArrayList<Integer>(Arrays.asList(a));
for (Integer integer : l) {
System.out.println(integer);
}
You can modify it easily to be of type Float and assign any initial value you want.
Related
I have a 2-dimensional ArrayList Object
private ArrayList<ArrayList<Short>> VOL_2D = new ArrayList<ArrayList<Short>>();
Now I want to call .ensureCapacity() on both the outer list and all the inner lists (The number of inner lists is know, but they are not initialized yet). For the outer list it is easy, I just define how many inner lists I want to fit inside.
Is there a nice way of calling this method on the inner lists? Or do I have to call it every time I initialize a new inner list?
There's no thing like "2-dimensional ArrayList Object". You have an ArrayList which stores ArrayList objects inside it. All of objects stored in the outer list may have different sizes, some of them may be null or subclasses of ArrayList. So you have to explicitly add enough ArrayList objects into the outer array list:
int n = // size of the outer list
int m = // size of the inner lists
private ArrayList<ArrayList<Short>> VOL_2D = new ArrayList<ArrayList<Short>>(n);
for(int i=0; i<n; i++)
VOL_2D.add(new ArrayList<>(m));
Please note that ensureCapacity does not actually add any elements to the list. It just resizes the internal array to fit the specified number of elements, so subsequent resizes will not be necessary. Creating an empty ArrayList and calling ensureCapacity right after this is meaningless: better to use the ArrayList(minCapacity) constructor which will do the same in more effective way. Anyways ensureCapacity is useful just to improve the performance. If you actually want to have elements inside these lists, you may use:
for(int i=0; i<n; i++) {
ArrayList<Short> inner = new ArrayList<>(m);
for(int j=0; j<m; j++)
inner.add(null); // or some other initial value
VOL_2D.add(inner);
}
Finally if you want to have two-dimensional ArrayList of fixed size, why not just create array like this?
private short[][] VOL_2D = new short[n][m];
It would be much more performant.
It seems that you don't understand what this construct really means. You see, those "inner" lists have no idea that they might be collected in some outer list. So there is no way to (easily) achieve what you are looking for.
One possibility though: you could extend ArrayList; and in your own class, you can overwrite all methods that would "add" an ArrayList ... you can do whatever you want; for example set the desired capcity.
You don't need to call ensureCapacity
It's just a method used for optimisation to avoid unnecessary reallocation of the underlying array data structure.
From the docs
An application can increase the capacity of an ArrayList instance
before adding a large number of elements using the ensureCapacity
operation. This may reduce the amount of incremental reallocation.
If the outer ArrayList size is known, and fixed then I would recommend you to use array instead of ArrayList, like below.
int size = 10;
ArrayList<Short>[] VOL_2D = new ArrayList<Short>[size];
Why do you need to call ensureCapacity(int minCapacity)? Could you elaborate your usecase? Because when you create instance you can specify the size of ArrayList. like below
VOL_2D[0] = new ArrayList<Short>(30);
This will invoke below constructor, and create an array size of 30
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
To answer your question, there is no single in-built method which will iterate all elements in list and call ensureCapacity.
You need to write code for this, like below
for(ArrayList<Short> vol : VOL_2D){
vol.ensureCapacity(30);
}
Remember this, before call ensureCapacity method, you need to initialize your ArrayList object (in your case all inner ArrayList object), otherwise you will end up with NullPointerException.
I am trying to convert an ArrayList to ArrayList. I am having actually a list of labels in Double and I want to create a list of Integers. I am trying to add the one to another but of course I need a casting process.
ArrayList<Integer> lab = new ArrayList<Integer>();
lab.addAll(labels.data); //labels.data is an Arraylist of Doubles.
How can I cast one list to another??
I ve tried this to add one by one:
ArrayList<Integer> lab = new ArrayList<Integer>();
for (int i = 0; i < labels.data.size(); i++) {
lab.set(i, labels.data.get(i).intValue());
}
But I received outOfBoundsError.
You can not convert List<Double> to List<Integer> directly. Loop on each Double object and call intValue() function to get the integer part of it. For e.g. 13.3 will give 13. I hope thats what you want.
for(Double d : labels.data){
lab.add(d.intValue());
}
First, is there any need for this to be an ArrayList particularly, or for these to be the wrapper classes instead of the primitives? If not, working with a simple array will avoid the overhead of boxing and unboxing, and of storing a lot of objects.
That aside, you'd probably want to loop over the list and cast each item to a double (or a Double), then add it to a new array (or ArrayList). There isn't a bulk operation for this.
You are getting outOfBoundsError because you are using set() instead of add(). set() is a replacement command and requires there to already be an object in that position.
Use Arraylist<Number>. A Number is a parent of both Double and Integer, so you would be able to add Doubles to your list and the Number.intValue() will convert (autoboxing) into Integer when required.
ArrayList<Number> list;
list.add(new Double(17.7));
Integer i = list.get(0).intValue(); // 18, rounding.
I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.
There are two sub-problems.
1- Comparing two huge arraylists
2- Sorting elements of arraylist based on the values of its object to achieve (1).
I have an ArrayList of objects of a class. i.e.
Class X
{
double x;
double y;
int sortVal;
}
ArrayList<X> alX = new ArrayList<X>(); //size = 10,000
ArrayList<Integer> myValue = new ArrayList<Integer>(); //size = 15
I want to check if myValue is present in sortVal.
X ob = new X();
for(i=0;i<myValue.size();i++)
{
for(j=0;j<alX.size();j++)
{
ob = alX.get(j)
**if (myValues.get(i) == ob.sortVal)**
}
}
As the size of the arraylist 'alX' is huge, it takes high computation time.
I thought the better way would be to sort the elemets of ArrayList alX based on the values of sortVal of Class X. By sorting, once sortVal is greater than myValue, I can break from the loop.
1) how can I sort the elements of arraylist alX based on the value 'sortVal'.
2) Is there a better approach, than sorting the arraylist, to compare the two values. i.e. (myValues.get(i) == alX.ob.sortVal)
[edit] Consider the values being,
ArrayList<X>:
x : 1,1,1,2,3,5,4,5
y : 2,4,6,4,4,6,2,1
sortVal: 10,20,30,10,10,20,30
ArrayList<Integer>:
myValue: 10,20,30
You could construct a Map<Integer, X> if sortVal values are unique or Map<Integer, Lists<X>> if they are not. This has a time complexity of O(n) instead or O(n * log n) which is the cost of doing a sort.
EDIT: This builds a MultiMap of keys and the set of objects for that key in one pass.
List<X> xs = ...
Map<Integer, Set<X>> mapBySortVal = new LinkedHashMap<>();
for(X x: xs) {
Set<X> set = mapBySortVal.get(x.sortVal);
if (set == null)
mapBySortVal.put(x.sortVal, set = new LinkedHashSet<>());
set.add(x);
}
for(Integer value: myValues) {
Set<X> xs = mapBySortVal.get(value);
if (xs != null)
// found some.
}
For your first question, you can sort a collection on anything you can think of by specifying the Comparator it should use (see Collections#sort)
Since you named your field sortVal, I would guess instances of this class can be sorted based on that value and you might want to implement the Comparable interface for that class. That way, you can use Collections#sort without having to specify the Comparator
Google guava get very useful functions. For ordering of arrays it provide com.google.common.collect.Ordering<T>.
For example:
Ordering<String> byLengthOrdering = new Ordering<String>() {
public int compare(String left, String right) {
return Ints.compare(left.length(), right.length());
}
};
List<String> sorted = byLengthOrdering.reverse().sortedCopy(sourceList);
Depending on your requirement there are 2 approaches:
Use Map, which orders its elements by natural order by default. But will take more memory.
OR
Sort using comparator. Will take more time.
Just look at their docs for explanation.
I have a method that returns Sets of sets.
Following is what I mean:
public static HashSet methodName(){
HashSet c= new HashSet();
c.add(x); //x is a HashSet of number
c.add(y); //y is a Hashset of numbers
return c;
}
After the method returns the collections, I enter it into an arraylist
ArrayList<HashSet> xxx= new ArrayList<Hashset>();
y=methodName();
xxx.add(y);
The method gets called couple of times and each time I enter sets of sets into the arraylist.
My question is. now I want to go through the arraylist and find the set that contains the smallest number of sets. How do I do that? Thanks so much in advance. Any help will be appreciated.
The size() method gives the cardinality of a HashSet. Simply write a Comparator<HashSet> and use Collections.max().
A simple way you to go through an array is through an Iterator. These are utilized in a foreach loop, which can be used when you know the type of elements used in an array (via generics). You can use that in your outer HashSet- containing ArrayList:
for (HashSet set : xxx) {
// you need to iterate over the elements in your HashSet here and determine which internal Set has the most elements
for ( Iterator iter = set.iterator(); iter.hasNext();) {
HashSet innerSet = (HashSet) iter.next();
// do the size test
}
}