I have got a loop with 2d list where I delete and add elements and want to add those temporary arraylists to the dimensions of another list.
Example,
// 2d list
List<List<Integer>> p = new ArrayList<List<Integer>>();
// 3d list
List<List<List<List<Integer>>>> list1 = new ArrayList<List<List<List<Integer>>>>();
// this compiles ok
list1.get(0).add(p);
but I get the following error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
You need to instantiate every list.. not just the one you are trying to access. Meaning that if you have a 2x2 matrix, you need 2 rows = 2 lists, and another list to hold them both, and so on if the matrix starts getting more complex.
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
List<Integer> row = new ArrayList<Integer>();
matrix.add(row);
Your "list1" object is actually 4d in your example, but those are not initialized, so when you ask "list1" to get the first (three dimensional) list inside, it does not exist at all (arrays in Java starts at 0 size), so there is nothing to add there.
You could do something like:
List<List<List<List<Integer>>>> list1 = new ArrayList<List<List<List<Integer>>>>();
List<List<List<Integer>>>> 3dlist = new ArrayList<List<List<Integer>>>();
list1.add(3dlist)
list1.get(0).add(p);
Now, using multidimensionnal arrays directly like this is not really practical - you may want to encapsulate them in an object.
Related
What I would like to achieve is to have a nested list (or array) with elements as lists (or arrays) consisting a pair of integers. This is to store some data and I would like to access those integers efficiently.
So I created a nested list in Java like this:
List combined = new ArrayList();
int x[] = new int[2];
List segl = Arrays.asList(x)
combined.addAll(segl);
the nested list will later be appended with more list like segl.
Now I want to return a element from combined. But with combined.get(0) the returned element data type is object instead of a list like segl, so I couldn't do anything with it (eg. return the single int element from segl. I have no idea how to change it to a list or array.
Based on the information you provided in the comments, you want to have 'List of Lists' where the second List has two elements. Unfortunately you can't use arrays as the generic type of a List. So what I think that you want to do is probably this:
// This is a List which holds other Lists.
List<List<Integer>> combined = new ArrayList<>();
List<Integer seql = new ArrayList<>(2); // Initialize with a size of 2.
// add justs adds seql to combined. addAll will add all elements of seql to combines
combined.add(segl);
This makes it so that combined.get(0) returns a List<Integer>.
If you are using an array you have two options:
// Using Arrays.asList(..)
List<List<Integer>> combined = new ArrayList<>();
Integer[] seql = new Integer[2];
combined.add(Arrays.asList(segl));
//If Integer[] is not possible.
List<List<Integer>> combined = new ArrayList<>();
int[] seql = new int[2];
List<Integer> seqlAsList = Arrays.stream(seql).boxed().collect(Collectors.toList());
combined.add(seqlAsList );
This question already has answers here:
I'm getting an error in my Java code but I can't see whats wrong with it. Help?
(5 answers)
Closed 5 years ago.
I created this arrayList:
Double[] arrayOfNumbers = new Double[List.size()];
And I try to add it numbers with this:
arrayOfNumbers.add(0.9);
This gives me an error message that says:
Cannot invoke add(double) on the array type Double[]
So, how can I add that value in this Double[] arraylist?
That is not an ArrayList. That is an array.
You can declare an arraylist of doubles as :
int initialCapacity = 20;
List<Double> doubles = new ArrayList<Double>(initialCapacity);
doubles.add(0.9);
You can add more than 20 values in an ArrayList even though the initial capacity is specified as 20.
But to declare an array and populate it:
double[] doublesArray = new doubles[20];
doubles[0] = 0.9;
doubles[1] = 0.5;
.....
doubles[19] = 0.7; // 19 is the last index for an array of size 20.
If you add more than 20 here, you will get ArrayIndexOutOfBoundsException
Double[] is not ArrayList to add to an array you can use :
Double[] arrayOfNumbers = new Double[List.size()];
arrayOfNumbers[0] = 0.9;
Instead to add to an ArrayList you can use :
List<Double> arrayOfNumbers = new ArrayList<>();
arrayOfNumbers.add(0.9);
Arrays and lists are different things. Arrays don't have an add method, but are assignable by the subscript ([]) operator:
arrayOfNumbers[0] = 0.9;
Double[] arrayOfNumbers = new Double[List.size()] is not a List
it is an array.
We declare arrays with [] and lists with <> and generics.
For example `
int[]arr=new int[3] is an array of 3 ints, but List<Integer>list=new ArrayList<>() is a list of integers(not primitive ints you CANNOTwrite code like this List<int>=new ArrayList<>()
Hope that helps!
java.util.List is a different that an array(which has limited predefined size).
you can't declare/perform as above you did in question, java compiler will complain if you do so.
you are phasing a error like,
Cannot invoke add(double) on the array type Double[]
because an array(arrayOfNumbers) do not having a such method(add) which you can execute on arrayOfNumbers.
However,
general syntax to initialize of an array of any type(here in example, Integer taken FYI) is likewise,
int intArray[] = {1,2,3}; // initialize at the time of creation
or
int arrayOfNumbers [] = new int[] {1, 2, 3};
or
intArray[index] = 1;
Moreover, you can switch from array to List & vice-versa as likewise,
List<Integer> list = java.util.Arrays.asList(arrayOfNumbers);
or
Integer [] intArray = list.toArray(new Integer[list.size()]);
A List is an Interface that extends another interface called Collection, so a List is-a Collection. An Interface defines and describes behavior, it defines a contract that another class must conform to, and one of the classes that does so is called java.util.ArrayList, and add() is one behaviour defined in the List contract, because a List must have the ability for things to be added to it. An ArrayList is one type of a List. What you have created is NOT an ArrayList, it is an Array.
An array is a primitive data structure, once created, it's size cannot be changed, If you wish to add a new element to an array you have to create a new array that is bigger, then transfer all elements from the old array to the new one. Under the covers an ArrayList does exactly that. THIS IS HOW YOU CREATE an ArrayList :
//a list of Objects of type `Double`
List<Double> listOfNumbers = new ArrayList<>();
if you wish to add an element to this list, you would do this :
listOfNumbers.add(5.2);
You do seem like you still need to read a beginners book and practice basic Java programming. I would like to suggest this playlist
This will really be helpful to you, and remember you can only learn something by doing it hands-on, NOT by just watching somebody else doing it.
I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.
Suppose I have a 2D list array which I declared as -
ArrayList<ArrayList<String>> seqList;
seqList = new ArrayList<ArrayList<String>>();
and the list contains the following elements -
[Mod5], [Mod5], [Mod5]
[Mod5, Mod10], [Mod5, Mod10]
[Mod5, Mod10, Mod8], [Mod5, Mod10, Mod8], [Mod5, Mod10, Mod8]
I want to extract the first elements of all the rows and save it in another list i.e. The result should be
[Mod5], [Mod5, Mod10], [Mod5, Mod10, Mod8]
Is there a possible way to do that?
Of course there is - a simple loop would do the trick:
ArrayList<String> res = new ArrayList<String>();
for (ArrayList<String> s : seqList)
res.add(s.get(0));
Note that the above code assumes that the lists are not empty. If that assumption is not true, add a check for an empty list before getting the initial element.
I am breaking my mind to find a solution to the following problem.
I have 4 different ArrayList that get their values from a Database.
They can have size from 0 (including) till what ever.
Each list may have different size and values also.
What I am trying to do effectively is :
Compare all the non 0 size lists and check if they have some common integers and what are those values.
Any ideas?
Thank you!
If you need a collection of common integers for all, excluding empty ones:
List<List<Integer>> lists = ...
Collection<Integer> common = new HashSet<Integer>(lists.get(0));
for (int i = 1; i < lists.size(); i++) {
if (!lists.get(i).isEmpty())
common.retainAll(lists.get(i));
}
at the end the common will contain integers that common for all of them.
You can use set intersection operations with your ArrayList objects.
Something like this:
List<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);
List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);
Now, l3 should have only common elements between l1 and l2.
You might be wanting to use apache commons CollectionUtils.intersection() to get the intersection of two collections...
Iteratively generate the intersection, and if it is not empty when you are done - you have a common element, and it is in this resulting collection.
Regarding empty lists: just check if its size() is 0, and if it is - skip this list.
You can do this. If you have multiple elements to search, put the search in a loop.
List aList = new ArrayList();
aList.add(new Integer(1));
if(aList !=null && !aList.isEmpty()) {
if(aList.contains(1)) {
System.out.println("got it");
}
}