Using the examples below the 2nd part I see how to add values to a single dim array. But the 2 dim array I dont yet understand. In the 1st example the 1,2,3 I need to get from a database. The DB part I have figured out but how to put in the values I dont know.
If I was using an array it would be
myarray[row][column] = value;
so how do I do this with the List?
mylist.add --- something?
List<double []> // creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
List<Double> myList = new ArrayList<Double>();
myList.add(1);
myList.add(2);
myList.add(3);
You should avoid using arrays as generic type parameters as you can easily end up with "unchecked" warnings. Use collections (typically ArrayList) instead.
So instead of this:
List<double []> // creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
Do something like this:
List<List<Double>> myList = new ArrayList<List<Double>>();
myList.add(new ArrayList<Double>());
myList.add(new ArrayList<Double>());
myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
Or to initialize together, you'd probably do something like:
List<List<Double>> myList = new ArrayList<List<Double>>();
List<Double> nested;
nested = new ArrayList<Double>();
nested.add(1);
nested.add(2);
nested.add(3);
myList.add(nested);
nested = new ArrayList<Double>();
nested.add(4);
nested.add(5);
nested.add(6);
myList.add(nested);
(You can add nested to myList before or after adding the elements to nested -- either way works so do whatever is clearer to you.)
To retrieve a specific element:
double value = myList.get(x).get(y);
To set a specific element:
myList.get(x).set(y, value);
This assumes that the list are already the right size, and that you just want to change the value of an existing element. (In other words, just like set behaves on a simple List.)
If you're talking about just doing inline initialization of a multidimensional array, I'm pretty sure you just use subsetted braces, like so:
Double array2D[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Do you want a collection-based solution for two-dimensional arrays? If so, then you're looking for a list of lists.
//Declaration
List<List<double[]>> twoDimList = new ArrayList<List<double>>();
//Adding values
twoDimList.add(new ArrayList<double>(1));
twoDimList.add(new ArrayList<double>(2));
twoDimList.add(new ArrayList<double>(3));
//Retrieving values
double value = twoDimList.get(1).get(1); //returns 1
List<T> myList = new ArrayList<T>();
T should be same. If T is double[] then it should be new ArrayList<double[]>()
then get(index) which is double array and get(index)[j] which is value. same logic with
d[i][j] = get(index)[j]
List<double []> myList = new ArrayList<double[]>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
System.out.println(myList.get(0)[1]);
Related
I'm trying to create a two dimensional ArrayList which will store ints, strings & booleans.
I've got as far as entering the first int, but I get a red squiggle and the error "int cannot be converted to ArrayList".
ArrayList[][] qarray= new ArrayList [10][5];
qarray[0][0]= 1;
BTW, googling the phrase "int cannot be converted to ArrayList" is giving me exactly six results.
The error is correct.
Your array type is ArrayList. You can insert only ArrayLists in that array.
If you want to store int's, your declaration should be.
int[][] qarray= new int [10][5];
And also, as someone commented, you cannot store strings and booleans in this array anymore.
ArrayList[][] qarray= new ArrayList [10][5];
Basically your code creates 2 dimensional array list objects (50 array list objects).
qarray[0][0]= 1;
And you are trying to assign integer, where you need to create a ArrayList object. It expects something like
qarray[0][0]= new ArrayList();
However this would not meet your objective. The following piece of code could meet your objectives:
ArrayList[] qarray = new ArrayList[10];
qarray[0]= new ArrayList();
qarray[0].add(1);
qarray[1]= new ArrayList();
qarray[1].add(true);
qarray[2]= new ArrayList();
qarray[2].add("hello");
Try like this:
List<Integer> qarray = new ArrayList<>();
qarray.add(1);
First I believe that you need array and not ArrayList. 2d array can be created as following.
int[][] arr = new int [10][10];
Your next problem is that you tried to assign int constant 1 to variable of other type. The following example shows how to assign int to element of array
arr [0][0] = 1;
According to javadoc, you can not create arrays of ArrayList. Use 2D array instead.
If you need 2D ArrayList anyway, you should have tried this way:
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<>();
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(5);
listOfLists.add(list1);
listOfLists.add(list2);
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
you wan to add int,String and boolean then you can use
ArrayList<ArrayList<Object>> listOfLists = new ArrayList<ArrayList<Object>>();
it will help you
ArrayList<Integer>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add(new Integer(10);
try like this.
I have values that I'd like to add into an ArrayList to keep track of what numbers have shown up.
The values are integers so I created an ArrayList;
ArrayList<Integer[]> list = new ArrayList<>();
int x = 5
list.add(x);
But I'm unable to add anything to the ArrayList using this method.
It works if I use Strings for the array list. Would I have to make it a String array and then somehow convert the array to integers?
EDIT: I have another question. I'd like the list to only hold 3 values. How would I do so?
List of Integer.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work
Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.
For Ex:
list.add(new Integer[3]);
In this way first entry of ArrayList is an integer array which can hold at max 3 values.
The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Here there are two different concepts that are merged togather in your question.
First : Add Integer array into List. Code is as follows.
List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);
Second : Add integer value in list.
List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}
When I input a certain data item (character here), I can access the elements it relates to like:
When I input 'A', it gives me access to the values (2, 3, 4, 5), e.g.:
A - 2,3,4,5
B - 6,7,9
C - 10, 11, 12, 13
D - 1,8
and so on...
Also that A, B, C, D could be any data item, int or even a string.
What I am thinking is, I can hold on a linear array and then each item in the array be the header for a linked list. Is this a correct and optimal solution to the above data structure required? Do we already have some data structure to do this?
The best solution is to use a Hash Table with an array (or list) in the table value.
Here an example in Java using HashMap
Map<String,Integer[]> theMap;
theMap = new HashMap<String,Integer[]>();
theMap.put("A",{2,3,4,5});
theMap.put("B",{6,7,9});
theMap.put("C",{10,11,12,13});
theMap.put("D",{1,8});
/* Access Values */
int two = theMap.get("A")[0];
You could also use ArrayList instead of arrays for your integers.
The code would become as follows:
ArrayList<Integer> listA = new ArrayList<Integer>();
listA.add(2);
listA.add(3);
listA.add(4);
listA.add(4);
ArrayList<Integer> listB = new ArrayList<String>();
listB.add(6);
listB.add(7);
listB.add(9);
ArrayList<Integer> listC = new ArrayList<Integer>();
listC.add(10);
listC.add(11);
listC.add(12);
listC.add(13);
ArrayList<Integer> listD = new ArrayList<Integer>();
listD.add(1);
listD.add(18);
Map<String,List<Integer>> theMap;
theMap = new HashMap<String,List<Integer>>();
theMap.put("A",listA);
theMap.put("B",listB);
theMap.put("C",listC);
theMap.put("D",listD);
/* Access Values */
int two = theMap.get("A").get(0);
Use a simple dictionary/map/associative array whose elements are lists (or sets). In Python, a collections.defaultdict can help here:
import collections
d = collections.defaultdict(list)
A,B,C,D = ['A', 8, 3.0, (1,2)]
d[A].extend([2, 3, 4])
d[A].append(5)
# d[A] is now [2,3,4,5]
I've a hashmap as shown below.
indexMap = new HashMap<String, ArrayList<Integer>>();
I could collect values from string like this,
String[] keysProblem2 = (String[]) indexMap.keySet().toArray(new String[0]);
How to collect values from arraylist? I tried doing like this,
Integer [] valuesProblem2 = (Integer[]) indexMap.values().toArray(new Integer[indexMap.size()]);
but was given an error like this,
java.lang.ArrayStoreException: java.lang.String
at java.util.AbstractCollection.toArray(Unknown Source)
indexMap.values() returns a Collection of ArrayList<Integer>s. You can't call .toArray(new Integer[indexMap.size()]) because it's a collection of ArrayList<Integer>, not Integers.
If you want to iterate through all ArrayLists, and create one large Integer[], then you'd have to do something like this:
ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>(indexMap.values());
ArrayList<Integer> allInts = new ArrayList<Integer>();
for(ArrayList<Integer> ints : arrays) {
allInts.addAll(ints);
}
Integer[] valuesProblem2 = (Integer[])allInts.toArray(new Integer[0]);
When I try to create an ArrayList myArrayList from an array, using Arrays.asList(myArray), I am not getting the List of elements in myArray. Instead I get list of Array.
The size of myArrayList is 1 . When I try to do myArrayList.toArray(), I am getting a two dimensional array. What to do to get the elements of myArray in a list? Is iterating the only option??
Firstly, the asList method is the right method:
Integer[] myArray = new Integer[3];
List<Integer> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 3, as expected
The problem may be that you are calling the varargs asList method in such a way that java is interpreting your parameter as the first varargs value (and not as an array of values).
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 1 - java invoked it as an array of Integer[]
To fix this problem, try casting your parameter as Object[] to force the varargs invocation, eg:
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList((Object[]) myArray); // Note cast here
System.out.println(myArrayList.size()); // prints 3, as desired
What is the type of myArray? You cannot use Arrays.asList with an array of primitive type (such as int[]). You need to use loop in that case.
There are different ways by which you can achieve it.3 example of converting array to arraylist and arraylist to array in java might help.
Would this work?
Object[] myArray = new Object[4]; //change this to whatever object you have
ArrayList<Object> list = new ArrayList<Object>();
for (Object thing : myArray) list.add(thing);
Try providing the generic type in the method call. The following gives me a list of 2 String elements.
String[] strings = new String[]{"1", "2"};
List<String> list = Arrays.<String>asList(strings);
System.out.println(list.size());