Arrays inside a Arraylist - arrays

i need to build up an ArrayList with Integer in new Arrays in it. How can I setup this and add items?
private final ArrayList<Integer>[] test;
test = new ArrayList<Integer>();
This won't work.
Thank you!

An array is an Object, and you can make lists of any object type - so you can make a List of arrays without doing anything special:
// Declare it and initialise as an empty list
List<Integer[]> list = new ArrayList<>();
// Add an item -- it's a new array
list.add(new Integer[5]);
// Access an item -- it's an array
Integer[] array = list.get(0);
Integer x = array[0];
I see few reasons to use arrays of Integer for most situations, however. An array of int is also an Object so you can use that just as well.
List<int[]> list = new ArrayList<>();
list.add(new int[5]);
One of the most common reasons for using the object Integer rather than the primitive int is that you can't have Lists of primitives. But you can have arrays of primitives, so if you're happy with the lesser expressive power of the array, by all means populate it with primitives.
Ask yourself why you want a List of arrays rather than a List of Lists, an array of arrays or an array of Lists, however.
Your question asks for "Arrays inside an ArrayList".
List<Integer[]> is a list of arrays (because, inside the <>, is Integer[]).
List<Integer>[] is an array of lists -- "ArrayLists inside an array" -- because the [] comes after the List<> declaration.
You can initialise your array of lists just like any other array, with new Type[length]:
// Declare it
List<Integer>[] array = new List<Integer>[5];
// Put something into an array element
array[3] = new ArrayList<Integer>();
// Access an element -- it's a List
List<Integer> list = array[3];
Integer x = list.get(0);

Looks like you want to create a 2-dimansional integer array.
I assume you have a special use case in which you need a primitive array ob ArrayList-Objects.
Anyways you can create such a thing like any other primitive array
like
ArrayList<Integer>[] test = new ArrayList[2];
and access/set it by index..
test[0] = new ArrayList<Integer>();
You also can fill the array on init...
ArrayList<Integer>[] test = new ArrayList[] {
new ArrayList<Integer>(),
new ArrayList<Integer>(),
new ArrayList<Integer>()
};

If we want Arrays inside List then -
class Test {
private final List<int[]> myList;
public Test() {
myList = new ArrayList<>();
}
public void add(int[] myArray) {
myList.add(myArray);
}
}
You are always allowed to initialize a final variable. The compiler makes sure that you can do it only once.

u can use like this for do this
private ArrayList<Integer>[] test ;
private void test(int n){
test=new ArrayList[n];
for(int i=0;i<n;i++){
test[i]=new ArrayList<Integer>();
test[i].add(100);
test[i].add(10);
test[i].add(10000);
test[i].add(1);
....
}
}

Related

Array of array double won't adding a new element in kotlin

I have array of array double but it won't add element after using .plusElementor .plus. code below inside from view model that returns it.data which is a list of object
Code
var ageEntry : Int
val dataObject : Array<Array<Double>> = arrayOf()
for (dataWeight in it.data!!){
ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
dataObject.plusElement(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
Log.d("DATA_SERIES_BARU", "setupViewInstance: ${dataObject.contentToString()}")
}
Log
The OP's proposed answer is subpar to say the least. If you need a mutable data structure, use a list not an array. I suggest something like this:
it.data?.fold(ArrayList<Array<Double>>()) { list, dataWeight ->
val ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
list.add(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
list
}
If you absolutely need an array at the end, you can easily convert it using toTypedArray().
Im adding this function to add array Element
fun <T> appendArray(arr: Array<T>, element: T): Array<T?> {
val array = arr.copyOf(arr.size + 1)
array[arr.size] = element
return array
}
then you can call it
appendArray(copyDataObject, arrayOf(ageEntry,arrayOf(arrayOf(2.0, 3.0)))

C# - Tuple arrays are mutable, but tuple lists are not. How do I get around this?

I have an array of value pairs I want to modify. I need to add and remove values from this array as well, so I used a list. When I tried to use a list, I encountered an error.
Error CS1612 - Cannot modify the return value of 'List<(int, float)>.this[int]' because it is not a variable
So I decided I would investigate. I tried using an array instead, and it... worked fine? The following code only throws an error on arr1[0].Item1 += 1;.
static void Main()
{
List<(int, float)> arr1 = new List<(int, float)>() { (0, 0) };
(int, float)[] arr2 = new (int, float)[1];
arr1[0].Item1 += 1; // This line
arr2[0].Item1 += 1;
}
Why are tuple arrays mutable, but lists are not? Is this because arrays are simple blocks of data you can modify easily, but lists have a lot of backend behind them that complicates things? Is there a simple way to get around this, or am I going to have to make my own custom class?
Why are tuple arrays mutable, but lists are not?
The list itself is mutable, but not in the way you're doing it. Note that this isn't anything specific to tuples - it's just the case for any mutable struct.
The list indexer getter returns a value (i.e. a copy of the tuple in your case) - so modifying that value wouldn't modify the copy in the list. The compiler is trying to avoid you making a change to a value that's about to be thrown away. Array access doesn't do that - arr2[0] refers to the variable within the array. (An array is effectively a collection of variables.)
If you want to mutate the list, you can have to fetch the tuple, mutate it, then put it back:
var tuple = arr1[0];
tuple.Item1++;
arr1[0] = tuple;
Note that this also explains why you can't use list access expressions as arguments for ref parameters, but you can do the equivalent for arrays:
public void Method(ref int x) => x++;
public void CallMethod()
{
var list = new List<int> { 0 };
var array = new int[] { 0 };
Method(ref list[0]); // Error
Method(ref array[0]); // Valid
}

Multidimensional array of Objects in Kotlin

I'm new in Kotlin, and I want to create a multi dimensional array of a custom class, with null permitted. Something like that
private var array_map = arrayOf<Array<Obstacle?>>()
...
array_map[1][2] = Obstacle()
How can I do it? Thank you!
In case you need the index of each element in the constructor of the elements of the array:
Declaration:
var matrix: Array<Array<Obstacle?>>
Instantiation and initialization:
matrix = Array(numRows) { row ->
Array(numCols) { col ->
Obstacle(row, col)
}
}
You can use private var arrayMap: Array<Array<Obstacle?>> = arrayOf(). Just wrap with as much Array<> as you need.
Not sure if this is what you want, but imagine that Obstacle is a custom class with a field num as below
data class Obstacle(var num: Int){}
A 2D array of the Obstacle object would be as below:
val array: Array<Obstacle?> = arrayOf(Obstacle(123), Obstacle(234))
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf(array)
println(arrayOfArray[0][0]) // would print Obstacle(num=123)
println(arrayOfArray[0][1]) // would print Obstacle(num=234)
So you should be declaring your 2D array as below
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf()
Your code will compile as is. The problem is just that array size can't be changed and arrayOf<Array<Obstacle?>>() creates an empty array, so array_map[1][2] = Obstacle() fails at runtime. (Unless you do array_map = ... somewhere between them. Note that you should prefer val arrayMap, which can't be reassigned, unless you have a specific reason to use var.)
If you want your array to start with nulls, there is arrayOfNulls in the standard library, but it only creates a single-dimensional array, and what you really need is an array of arrays of nulls. You can write a helper function:
inline fun <reified T> matrixOfNulls(n: Int, m: Int) = Array(n) { arrayOfNulls<T>(m) }
private val arrayMap = matrixOfNulls<Obstacle>(5, 5) // example arguments
The approach I always use for this case is:
arr2D = Array(sizeA) { Array(sizeB) { content } }
Note I replaced the sizes by fields names to illustrate that each number/field represents the width and height length of each dimension of the 2D array.
Also, content should be replaced by the main content you want to fill in each coordinate, in your case seems you aims to setup with Obstacle() instances. If you want fill this content in other moment put null or a quick Any() reference.
In this last case, after creating that you can simply perform to set the itens:
arr2D[1][2] = Obstacle()

Index of an element in ArrayList of arrays

I have a list of two-element arrays that looks like this:
ArrayList<int[]> list = new ArrayList<int[]>();
I can get an element from this list using list.get(), but trying get the index of a known element doesn't work:
int[] array = list.get(0); //returns an array
int index = list.indexOf(array); //returns -1
I am using Processing 3.2.1
What am I doing wrong?
This will work:
ArrayList<int[]> list = new ArrayList<int[]>();
list.add(new int[]{1, 2});
int[] array = list.get(0);
int index = list.indexOf(array);
println(index);
This will not:
ArrayList<int[]> list = new ArrayList<int[]>();
list.add(new int[]{1, 2});
int[] array = new int[]{1, 2};
int index = list.indexOf(array);
println(index);
The indexOf() function uses the equals() function to figure out whether an object equals an element at each index. Unfortunately, arrays don't behave like you might expect, so two different arrays that have the same elements are not equal!
int[] arrayOne = {1, 2};
int[] arrayTwo = {1, 2};
println(arrayOne.equals(arrayTwo));
This is because arrays use instance equality, so arrays are only equal if they are the same exact array! That's why the first code block works, but the second one does not.
One way around this is to create a wrapper object that contains your arrays, and then override the equals() function to actually compare the elements in your arrays. But since your arrays only have two indexes, why don't you just create a class that has two variables, and then override the equals function? Or just use a PVector instance.

Converting an int array list to an int array

EDIT:
I am trying to add elements read from a txt document line by line into an array list then convert that array list into an array. Although I am getting errors with my code. It doesnt like the int[] a = lines.toArray(new int[lines.size()]);.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
List<Integer> lines = new ArrayList<Integer>();
File file = new File("10_Random.txt");
try {
Scanner sc = new Scanner(file);
//int line = null;
while (sc.hasNextLine()) {
int i = sc.nextInt();
lines.add(i);
//System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
int[] a = lines.toArray(new int[lines.size()]);
}
}
Edit2: Thanks chaitanya10! all fixed.
int line= null; is wrong,
"null is a special literal that can be of any object reference type".you cant assign null to primitive variables in java like (int, byte, float...). null can only be assigned to objects . remember thatnullis the default vale forobjects` when you don't initialize them.
if you wanna access int as an object use Integer.
Integer line= null;//nowthis would compile
and to convert an list onto array do this.
List.toArray(T[] t) method returns an Object.
do like below.
Integer[] array = lines.toArray(new Integer[lines.size()])
and also your List accepts int[] array and you are tryig to add an int into the list .
change your List declaration like this
List<Integer> lines = new ArrayLis<Integer>();
To print the elements in the array you have to iterate over it
for(int i=0; i<a.length;i++){
system.out.println(a[i])
}
you seem to be a beginner in java. strongly recommend you tohereread about java basic
Two main problems.
You can't assign null to an int. null is a pointer value, and ints in Java are always handled by value, not by reference. Objects can be null, primitive values like int and double can't.
The type declaration of your ArrayList is wrong. The way you're assigning it, each element of the list is expected to be an array of ints. I don't think that's really what you want - the each element is just one int value, so that the list as a whole is analogous to an array.
The second bullet is the reason behind your second and third errors, which I think you'd probably see if you read the error messages all the way through (it's a TypeMismatch error, right?). With your list parameterized to int[], the add method is expecting everything that's added to be of the type int[]. But line is only an int. Similarly, the toArray() method returns an array of whatever type the list is parameterized with. Since you have a list of arrays, toArray() will return an array of arrays. Its return type in this case is int[][], which can't be assigned to int[] a because the type doesn't match.
This should get your code to compile, but it doesn't get into the other issues of validation and whatnot that you have to worry about any time you have input... but for now I'm just going to assume that you've already vetted the input file.
You can use IntStream:
int[] arr = {15, 13, 7, 4, 1, 10, 0, 7, 7, 12, 15};
List<Integer> arrayList = IntStream.of(arr).boxed().collect(Collectors.toList());
System.out.println(arrayList);

Resources