Select specific item in Arraylist of arrays - arrays

I'm working with Processing and I have an Arraylist of arrays
ArrayList< ICurve []> c = new ArrayList< ICurve []> ();
I need to select a specific item in a specific array of my arraylist, but I can't understand how to do it. I know how to iterate inside the arraylist with the for cycle, but I can't understand how to select the item with a specific index.
Thanks in advance for your help!

An Arraylist of arrays returns an array, so just use bracket notation:
ArrayList <Integer[]> a = new ArrayList <Integer[]> ();
void setup(){
a.add(new Integer[] {1,2,3});
println(a.get(0)[1]);// prints 2
}

ArrayList< int[] > myArrayList = new ArrayList< int[]> ();
void setup()
{
int[] myArray = {0, 1, 2, 3};
myArrayList.add(myArray);
println(myArrayList.get(0)[0]);
}
I've used a primitive datatype in this example, but the same principle applies.

Related

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()

Arrays inside a Arraylist

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);
....
}
}

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);

Using constructors with arrays in D

How do you call constructors when allocating an array with new?
For example, in the following code how would I call the constructor for each instantiation of A, initialising b to 5 for all 10 elements?
void main() {
A[] a = new A[10];
}
class A {
int b;
this(int init) {
b = init;
}
}
I'm guessing it's not possible, but I can hope...
a simple loop should do (and it's the most readable)
foreach(ref el;a){
el=new A(5);
}
or you can use the array initializer:
A[] a=[new A(5),new A(5),new A(5),new A(5),new A(5),
new A(5),new A(5),new A(5),new A(5),new A(5)];
If you're dealing with a value type, you can use std.array.replicate.
auto a = replicate([5], 50);
would create an int[] of length 50 where each element is 5. You can do the same with a reference type, but all of the elements are going to refer to the same object.
auto a = replicate([new A(5)], 50);
will only call A's constructor once, and you'll end up with an A[] where all of the elements refer to the same object. If you want them to refer to separate objects, you're either going to have to set each element individually
auto a = new A[](50);
foreach(ref e; a)
e = new A(5);
or initialize the whole array with a literal
auto a = [new A(5), new A(5), new A(5)];
But that clearly will only work for relatively small arrays.
If you really want to do it in one line, you could write a macro to do it for you. I've borrowed code for the actual initialisation from the other answers.
template allocate(T) {
T[] allocate(int size, int arg) {
T[] result = new T[size];
foreach(ref el; result)
el=new T(arg);
return result;
}
}
Then you can allocate an entire array of 10 elements at once with:
A[] a = allocate!(A)(10, 5);
Of course this has fixed constructor arguments, but you could probably do something with variadic arguments to the template and some mixins to generate the correct constructor call.

Resources