Adding string to ArrayList<ArrayList<String[]>> - java

We can add a string to an ArrayList<String[]> as:
ArrayList<String[]> array1 = new ArrayList<>();
array1.add(new String[]{"word"});
But how can we add a string to an ArrayList<ArrayList<String[]>> directly without creating array1. Something like:
array2.add(new ArrayList<>(new String[]{"hello"}));

You could use
array2.add(new ArrayList<>(Arrays.<String[]>asList(new String[]{"hello"})));
There is no ArrayList(ArrayOfElements) constructor, but we can use ArrayList(CollectionOfElementsToCopy) constructor. With that all we need to do is wrap elements into some collection. For that we can use Arrays.asList(elements).
Problem with Arrays.asList is that it uses T... varargs which by default represents array of elements. If we want to tell that array is element we can do it by explicitly specifying <String[]> as method generic type.

Related

Java: how to create a list cons that accepts lists for the first element

When I create a Java list and I want that the head is a list, should it print a [[-1,0],1,2,3,4] or its alright it just leave the sublist [-1, 0] as two separated elements like [-1, 0, 1, 2,3,4] and, how can I get the first structure as an aswer.
From your post I guess you are asking about how to create a list "construct" in Java which contains both list and non-list elements.
In Java all elements of your list/array need to have the same type. In the example you posted ([[-1,0],1,2,3,4]), the elements are not all the same type. What you have is this: [List<Integer>, Integer, Integer, Integer, Integer]. The first one is different, which isn't allowed in Java.
So, what you need to do is make it so that all elements of your list/array are the same type.
For your case, where there are only integers in your list, the easiest thing to do is to change your types to this: [List<Integer>, List<Integer>, List<Integer>, List<Integer>, List<Integer>] (with your specific values: [[-1,0],[1],[2],[3],[4]]). Instead of a list of List<Integer> and Integer, you now have a list containing only List<Integer> (some of your lists happen to contain only 1 element, but that is ok).
This is called a "two-dimensional list" and depending on whether you want to code it with arrays or java.util.Lists you can code it in one of the following ways:
// with arrays
int[] myTwoDarr = int[5][];
myTwoDarr[0] = new int[]{-1, 0};
myTwoDarr[1] = new int[]{1};
myTwoDarr[2] = new int[]{2};
myTwoDarr[3] = new int[]{3};
myTwoDarr[4] = new int[]{4};
// With Lists
List<List<Integer>> myList = new LinkedList<>();
List<Integer> nestedList1 = new LinkedList<>();
nestedList.add(-1);
nestedList.add(0);
myList.add(nestedList1);
List<Integer> nestedList2 = new LinkedList<>();
nestedList2.add(1);
myList.add(nestedList2);
...etc...
Now, if you absolutely must have different kinds of data in your list, you can create a list of Object instead.
In Java Object is a type from which all non-primitive types inherit. Thus, as long as something is not a primitive, it is an Object and can go in a list of Object. This will allow you to put any kind of data in the elements of your list. Using Object allows you to have a list of all the same type which looks like this: [Object, Object, Object, Object, Object]. But, now Java does not know the specific types you actually have stored in your elements so you will need to type cast when getting them.
Here's an example using a java.util.List:
List<Object> myList = new LinkedList<>();
List<Integer> nestedList = new LinkedList<>();
nestedList.add(-1);
nestedList.add(0);
myList.add(nestedList);
myList.add(1);
myList.add("a string");
// You need to cast when taking elements out of the list.
List<Integer> newNest = (List<Integer>) myList.get(0);
Integer myInt = (Integer) myList.get(1);
String myString = (String) myList.get(2);
Since all your base data types are the same (Integer/int) I recommend avoiding the Object list method and going with the 2D list. It's simpler and less error prone to not do all this casting.

Can I create a list of array with Arrays.asList?

Say I want to create a List which contains Integer[] arrays. But
Integer[] foo = {1,2,3};
List<Integer[]> bar = Arrays.asList(foo);
The second line wouldn't compile, because Arrays.asList(foo) will return a List with three Integer elements(namely 1, 2, 3), not a List with a single Integer[] element.
Since the documentation states the parameter of asList method as varargs of type T, I don't understand why the compiler doesn't interpret the second line as single argument of type Integer[] given. How do I get a List of single Array element?
List<Integer[]> bar = new ArrayList<Integer[]>(Arrays.asList(foo));
This is what I actually wanted to do, but it also doesn't compile, for the same reason I believe.
A very similar question was just asked the other day, but I suppose this is different enough for it not to be a duplicate. You need to explicitly specify the generic type for it to compile, like so:
Integer[] foo = {1, 2, 3};
List<Integer[]> list = Arrays.<Integer[]>asList(foo);
Unless you actually need the ability to set the element to a different array, you can use:
List<Integer[]> list = Collections.singletonList(foo);
This is more efficient, because it is specialized to just holding one element: no array has to be created, contains is simply checking equality, size is always 1 etc.
No. Arrays.asList takes a projection of your current array and flattens the first dimension into a List. Since you only have one dimension, all of those elements get collected into the list.
You could do it if you had an Integer[][].
Note: asList accepts a vararg of T (so T...), which is effectively T[]. If you substitute that with Integer[][], you get Integer[], since one dimension of your Integer[][] will satisfy T...'s type requirement.
Varargs in java is just a syntactic sugar in Java. So, there is no difference between.
Arrays.asList(1,2,3) and Arrays.asList(new Integer[]{1,2,3}).
So what you can do like below to solve your problem.
Integer[][] foo = {{1,2,3}};
List<Integer[]> bar = Arrays.asList(foo);
Arrays.asList() generates list of contents of array passed as argument. If you need to create list of arrays, you need to pass to this method array of arrays (e.g. Integer[][]).
When you pass to method Integer[] as argument instead of Integer[][] , it makes a list of contents of that array (in that case these are Integers not arrays of Integers).
Wrapping your array in another array will achieve what you want:
Integer[] foo = {1,2,3};
List<Integer[]> bar = Arrays.asList(new Integer[][]{foo});
// OR
Integer[][] foo = {{1,2,3}};
List<Integer[]> bar = Arrays.asList(foo);
You could also just manually set the first element: (I'd probably say this is more readable, but opinions may vary)
Integer[] foo = {1,2,3};
List<Integer[]> bar = new ArrayList<>();
bar.set(0, foo);

define an array which its elements are object in java

I want to define an array which its elements are object in java and i can use for ex this method:
public void add(Object elem);
Can anyone help me on this?
A literal object array is defined as any other array.
Object[] objects = new Object[10];
Though, more likely, you are looking for something like ArrayList
List<Object> object = new ArrayList<Object>();
Which will give you the .add functionality because it's a List.
Objecttype objects= new Objecttype [initial size]
Why you want to use arrays. go for ArrayList in which you don't bother to define your initial size also it provides its own add method
Defining an array of objects is just like defining any other array
Object[] objectList = new Object[MAX_LIMIT];
for(int i=0;i<objectList.length;i++){
objectList[i] = new ANY_DATA_TYPE();
}

How do i convert from a set to a list within a method call?

I would like to convert from a set to a List within a method call. Right now this is what i do :
List<Integer> lrsIdList = new ArrayList<Integer>();
lrsIdList.addAll(repaymentMap.keySet());
getObjects(lrsIdList)
How do i do this?
Assuming your repaymentMap.keySet() returns the Set<Integer>
getObjects(new ArrayList<Integer>(repaymentMap.keySet()));
You can convert the Set to a List by passing the Set instance into the constructor of a List implementation class such as ArrayList.
List<String> list = new ArrayList<String>(hashset);

using toArray with ArrayList of custom objects

Is there a way to use the toArray() method on an ArrayList<CustomObject>?
From what I see, it can only be used with Object
You need to pass in an array of CustomObject in order to get one back. The parameter-free ArrayList.toArray() call returns an Object[], but the parameterized version T[] ArrayList<T>.toArray(T[]) returns what you expect. If you size the array you pass as a parameter correctly then the call will use the array you pass rather than allocate another one, e.g.
ArrayList<CustomObject> foo;
//...
CustomObject[] bar = foo.toArray(new CustomObject[foo.size()]);
Use:
CustomObject[] customObjects = myList.toArray(new CustomObject[myList.size()])
CustomObj[] customArray = new CustomObj[size];
customArray = (CustomObj[])ArrayListObj.toArray(customArray);

Categories

Resources